在Express路由(猫鼬,MongoDB,Express)中更新文档中的属性

我已经使用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)
  };
});

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

jxs121000 回答:在Express路由(猫鼬,MongoDB,Express)中更新文档中的属性

尝试用

替换user.lastConnection = new Date();
user.update({ lastConnection: new Date() })
   .then( updatedUser => {
        console.log(updatedUser)
        // put jwt.sign code here
    })
本文链接:https://www.f2er.com/3169981.html

大家都在问