You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

注册时加密密码未存入MongoDB且登录无法查询用户问题

问题分析与解决方案

核心问题1:加密密码未存入MongoDB

原因是Mongoose Schema字段大小写不匹配:

  • 你的./registration文件中,Schema定义的密码字段是Password(首字母大写)
  • 但注册接口创建用户时,赋值的字段是password: encryptedPassword(全小写)
    Mongoose对字段名大小写严格敏感,因此数据库中不会生成password字段,仅保留未赋值的Password字段,最终导致密码丢失。

核心问题2:登录触发「User not found」错误

存在两个关键诱因:

  1. 路由大小写不匹配:前端登录请求的URL是/Login(大写L),但后端定义的登录接口是/login(小写l),HTTP路由默认大小写敏感,导致请求无法匹配到正确接口,后端返回的非预期响应被前端错误解析为「User not found」。
  2. 即使路由匹配,由于密码字段名不匹配,数据库中用户文档的password字段不存在,后续登录验证也会失败。

修复步骤

  1. 统一密码字段名
    修改./registration中的Schema,将Password改为小写password,与注册接口的赋值字段保持一致:
const UserDetailsSchema = new mongoose.Schema(
{
    user: {type: String, unique: true},
    email: {type: String, unique: true},
    phone: String,
    password: String, // 改为小写
    joined: { type: Date, default: Date.now },
},
{
    collection: "UserInfo",
}
);

注意:若数据库已有旧用户文档,需手动将文档中的Password字段重命名为password,或重新注册测试用户。

  1. 统一登录路由大小写
    修改前端登录请求的URL,将/Login改为/login,与后端接口路由一致:
fetch("http://localhost:4000/login", { // 改为小写login
    method: "POST",
    crossDomain: true,
    headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        "Access-Control-Allow-Origin": "*",
    },
    body: JSON.stringify({
        email,
        password,
    }),
})
  1. 调试优化建议
  • 在后端接口的catch块中打印错误信息,便于快速定位问题:
catch (error) {
    console.error(error); // 新增错误打印
    res.send({ status: "error" });
}
  • 前端增加请求错误捕获,处理网络异常或非预期响应:
fetch(...)
.then((res) => {
    if (!res.ok) throw new Error(`请求失败,状态码:${res.status}`);
    return res.json();
})
.then((data) => { ... })
.catch((err) => {
    console.error("请求出错:", err);
    alert("登录失败,请检查控制台信息");
});

内容的提问来源于stack exchange,提问作者Justin Eastin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 06:35:38