【问题标题】:Mongoose return "new ObjectId("//id")" instead of just the idMongoose 返回 "new ObjectId("//id")" 而不仅仅是 id
【发布时间】:2021-09-21 22:25:48
【问题描述】:

我正在尝试执行我的登录功能(我正在使用 bcrypt 和 jsonwebtoken)问题是 console.log (user._id) 返回我 "new ObjectId (" 6148f043ebbaa0ab41ac8499 ")" 而不仅仅是 "6148f043ebbaa0ab41ac8499" ,创建令牌会更容易。

  module.exports.login = async (req, res) => {
     const { email, password } = req.body;
    
      // Compare the req.body.password to the hashed password in DB
      const user = await UserModel.findOne({ email: email });
      const match = await bcrypt.compare(password, user.password);
    
      if (match) {
        try {
          const user = await UserModel.findOne({ email: email });
          console.log(user._id);
    
          // Assign a token
          const token = jwt.sign({ userId: user._id }, process.env.LOGIN_TOKEN, {
            expiresIn: "1h",
          });
          console.log(token);
          res.cookie("jwt", token, { httpOnly: true});
          res.status(200).json({ user: user._id });
        } catch (err) {
          res.status(500).json(err);
        }
      } else {
        res.status(500).json({ message: "error!!!" });
      }
    };

请问如何解决?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    这是正常行为。既然你有一个ObjectId,你可以通过调用toHexString() 方法将其转换为字符串。我还修改了代码以检查未定义的用户,并删除了查找用户的额外调用,因为您已经在上一行中做了。请查看更新代码:

    module.exports.login = async (req, res) => {
      const { email, password } = req.body;
       const user = await UserModel.findOne({ email: email });
    
       if (!user) {
         return res.status(400).json({ message: "Unauthorised"});
       }
     
       // Compare the req.body.password to the hashed password in DB
       const match = await bcrypt.compare(password, user.password);
     
       if (match) {
         try {
          //  Convert user id (ObjectId) to a string
           const userId = user._id.toHexString();
          //  Now user id is a string
           console.log(userId);
     
           // Assign a token
           const token = jwt.sign({ userId }, process.env.LOGIN_TOKEN, {
             expiresIn: "1h",
           });
           console.log(token);
           res.cookie("jwt", token, { httpOnly: true});
           res.status(200).json({ user });
         } catch (err) {
           res.status(500).json(err);
         }
       } else {
         res.status(400).json({ message: "Unauthorised" });
       }
     };
    

    【讨论】:

    • 它有效,我必须承认你的代码比我的更漂亮,哈哈。非常感谢!
    猜你喜欢
    • 2020-01-20
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2015-08-26
    相关资源
    最近更新 更多