【问题标题】:Update a property in document in an Express route (Mongoose, MongoDB, Express)在 Express 路由(Mongoose、MongoDB、Express)中更新文档中的属性
【发布时间】:2019-11-04 13:01:52
【问题描述】:

我已经使用 Express、MongoDB 和 Mongoose 成功设置了注册和登录功能。

一旦用户文档的lastConnection 属性中接受了用户凭据,我想记录用户上次访问该站点的时间,

我尝试过,但“lastConnection”为空(请参阅下面我添加评论的行)

router.post("/login", async function(req, res) {
  const { errors, isValid } = validateLoginInput(req.body);

  if (!isValid) {
    return res.status(400).json(errors);
  }

  const email = req.body.email;
  const password = req.body.password;

  const user = await User.findOne({ email }).then(user => {
    if (!user) {
      errors.email = "Email already exists";
    }

    console.log("user ", user); <-- returns an object with the datas of user

    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        const payload = {
          id: user.id,
          name: user.name
        };

        user.lastConnection = new Date(); <-- doesn't work

        jwt.sign(
          payload,
          keys.secretOrKey,
          {
            expiresIn: 7200
          },
          (err, token) => {
            res.json({
              success: true,
              token: "Bearer " + token
            });
          }
        );
      } else {
        errors.password = "Password is not correct";
        // return res
        //   .status(400)
        //   .json({ passwordincorrect: "Password incorrect" });
      }
    });
  });

  return {
    errors,
    isValid: isEmpty(errors)
  };
});

有什么想法吗?我想我必须做一个更新,但我不知道把它放在哪里

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    尝试用

    替换 user.lastConnection = new Date();
    user.update({ lastConnection: new Date() })
       .then( updatedUser => {
            console.log(updatedUser)
            // put jwt.sign code here
        })
    

    【讨论】:

    • 我明天试试,因为我要睡觉了,我让你知道这个问题,谢谢
    • 听起来不错。澄清一下,我们是通过控制台记录 updatedUser 对象来确定用户是否真的被更新了,你也可以使用 MongoDB Compass 或其他方法来验证
    • 我的荣幸,祝你好运!
    猜你喜欢
    • 2018-12-29
    • 2022-07-12
    • 2018-04-01
    • 2021-03-14
    • 2020-09-03
    • 2016-07-27
    • 1970-01-01
    • 2019-05-07
    • 2017-04-14
    相关资源
    最近更新 更多