我正在try 将用户登录到我的数据库.当我让用户登录时,它返回数据库中的第一个用户ID,而不是登录的用户.我已经为这个问题挣扎了一段时间,真的走到了死胡同.

这是我的帖子路由,让用户登录:

// login
router.post("/login", async (req, res) => {
  const user = await User.findOne({
    email: req.body.email,
  });
  const secret = process.env.SECRET;
  if (!user) {
    return res.status(400).send("the user not found!");
  }
  if (user && bcrypt.compareSync(req.body.password, user.passwordHash)) {
    const token = jwt.sign(
      {
        userId: user.id,
        isAdmin: user.isAdmin,
      },
      secret,
      { expiresIn: "1d" }
    );
    res.status(200).send({ user: user.email, token: token });
  } else {
    res.status(400).send("password is wrong!");
  }
});

这将返回错误的用户. 当我使用userId查询端点获取用户配置文件时,它会获得正确的信息.所以这和数据库没有任何关系.

这是应用程序中的呼叫.

  const handleSubmit = () => {
    axios
      .post(`${baseURL}users/login`, {
        email: email,
        passwordHash: password,
      })
      .then(res => {
        console.log('USER ID TOKEN', res.data.token);
        setbearerToken(res.data.token);
        AsyncStorage.setItem('bearerToken', res.data.token);
        const decoded = decode(res.data.token);
        setTokenID(decoded.userId);
        dispatch(setUser(res.data));
      });
  };

用户.js模型

const userSchema = mongoose.Schema({
    contactName: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 50
    },
    phone: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 50
    },
    passwordHash: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 1024
    },
    token: {
        type: String,
    },
    isAdmin: {
        type: Boolean,
        default: false
    },
    clubName: {
        type: String,
        required: true,
    },
    clubAddress: {
        type: String,
        required: true,
    },
    clubEmail: {
        type: String,
        required: true,
    },
    clubPhone: {
        type: String,
        required: true,
    },
    clubWebsite: {
        type: String,
        required: true,
    },
    clubContact: {
        type: String,
        required: true,
    },
})

推荐答案

您的架构没有可供筛选的字段email.

const user = await User.findOne({
    email: req.body.email,
});

也许你可以试试clubEmail场比赛.我重现了这个行为,如果模式中不存在该字段,Mongoose就会忽略过滤器,只返回集合中的第一个文档.

例如.

const userSchema = new Schema(
    {
        name: String,
        age: Number
    }
)

const User = mongoose.model('User', userSchema);

User.findOne({name: "Superman"}, ...

返回名为"Superman"的用户.

const userSchema = new Schema(
    {
        name: String,
        age: Number
    }
)

const User = mongoose.model('User', userSchema);

User.findOne({xname: "Superman"}, ...

但是,当在过滤文档中使用xname时,该查询返回测试集合中的第一个文档(它不是超人),而过滤文档既不存在于我的模式中,也不存在于集合As字段中.

在这里也可以看到类似的问题:Model.find Mongoose 6.012 always return all documents even though having filter

报告的问题:https://github.com/Automattic/mongoose/issues/10763

Mongoose 6迁移指南: https://mongoosejs.com/docs/migrating_to_6.html#strictquery-is-removed-and-replaced-by-strict

Node.js相关问答推荐

使用Vite和ReactJS时,在哪里设置NODE_OPTIONS?

在渲染上部署Node.js服务器时出错:MODULE_NOT_FOUND

使用NodeJS在S3上传文件时的格式问题

如何将我的Redis客户端配置为在禁用群集模式的情况下使用读取副本?

如何使用Nextjs路由从下一步/导航在新选项卡中通过";router.ush";打开链接

模块';"; node :流程&没有导出的成员';dlopen';

类扩展值[object object]不是构造函数或null

为什么 mongoose 没有常规数组方法

从数据库读取数据并将其作为可下载的 zip 文件发送

discordjs如何添加所有意图/权限

如何刷新 youtube-data-api v3 的访问令牌

Mongoose,如何一次更新多个?

try 运行迁移时的 Typeorm:缺少必需的参数:dataSource

调用 require 时的 const vs let

在 Jade 包含中使用变量

需要 node-gyp 的 npm install 在 Windows 上失败

Forever + Nodemon 一起运行

如何使用 cookie 创建 HTTP 客户端请求?

node.js 在控制台上显示未定义

在 Node.js 中混合使用 JavaScript 和 TypeScript