Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在Express route(Mongoose、MongoDB、Express)中更新文档中的属性_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Node.js 在Express route(Mongoose、MongoDB、Express)中更新文档中的属性

Node.js 在Express route(Mongoose、MongoDB、Express)中更新文档中的属性,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我已经使用Express、MongoDB和Mongoose成功地设置了注册和登录功能 我想在用户文档的lastConnection属性中接受用户的凭据后记录用户上次访问站点的时间 我尝试了,但lastConnection为空。请参见下面我添加注释的行 router.post("/login", async function(req, res) { const { errors, isValid } = validateLoginInput(req.body); if (!isValid

我已经使用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)
  };
});
有什么想法吗?我想我必须做一个更新,但我不知道把它放在哪里

尝试替换用户。lastConnection=newdate;与

user.update{lastConnection:new Date} .then UpdateUser=>{ console.LogUpdateUser //在这里输入jwt.sign代码 }
我明天会试试,因为我要睡觉了,我会让你知道这个问题的,谢谢。很好。为了澄清,我们正在控制台上记录UpdateUser对象,以确定用户是否已实际更新,您也可以使用MongoDB Compass或其他方法验证我的意愿,祝您好运!