数组中的猫鼬验证系统元素未删除

时间:2020-08-30 09:29:35

标签: javascript node.js mongodb validation mongoose

我目前正在使用Node,Express和Mongoose开发一个验证系统,但遇到了一些问题。在我的模式中,我有一个与用户相关联的verificationId,因此当他们单击通过电子邮件发送给他们的链接时,它可以检查该VerificationId是否与数据库中的那个相同。所有这些都可以正常工作,但是由于现在不再需要该方法,我无法弄清楚如何删除它。

当前,它正在验证用户,但并未删除VerificationId。我曾尝试用$ pull方法弄乱,但它没有任何成功。任何帮助将不胜感激!

//User verification page
app.get("/verify/users/:verifiedId", (req, res) => {
  const verifiedId = req.params.verifiedId;
  //Check to see if the verificationHash the user was sent is the same as the one stored for them in the database
  User.findOne({ verificationHash: verifiedId }, (err, result) => {
    if (!err) {
      console.log(verifiedId);
      console.log(result);
      const originalValue = { isVerified: false };
      const newValue = { isVerified: true };
      //Verify the user in the database
      User.findOneAndUpdate(originalValue, newValue, (err) => {
        if (!err) {
          if (newValue) {
            res.redirect("/success");
          } else {
            res.send(
              "There was an error verifying your account. Please try again."
            );
          }
        } else {
          res.send(500, { error: err });
        }
      });
    } else {
      res.send(err);
      console.log(err);
      console.log(verifiedId);
    }
    //Delete the verificationHash from the user in the database
    User.findOneAndUpdate(
      { verificationHash: verifiedId },
      { $pull: { verificationHash: { verificationHash: verifiedId } } },
      { new: true }
    )  });
});

1 个答案:

答案 0 :(得分:0)

我对这个答案不太确定,但尝试使用unset operator

User.findOneAndUpdate(
  { verificationHash: verifiedId },
  { { $unset: {"verificationHash": ""} },
  { new: true }
) 

否则可能会起作用(将值设置为null

User.findOneAndUpdate(
  { verificationHash: verifiedId },
  { verificationHash: null },
  { new: true }
)