【问题标题】:Mongoose validation system element in array not being deleted未删除数组中的猫鼬验证系统元素
【发布时间】:2020-12-18 16:46:12
【问题描述】:

我目前正在使用 Node、Express 和 Mongoose 开发一个验证系统,但遇到了一些问题。在我的架构中,我有一个与用户关联的验证 ID,因此当他们单击通过电子邮件发送给他们的链接时,它可以检查该验证 ID 是否与数据库中的相同。所有这些都可以正常工作,但我不知道如何删除验证 ID,因为它不再需要了。

目前它正在验证用户但不删除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 }
    )  });
});

【问题讨论】:

    标签: javascript node.js mongodb validation mongoose


    【解决方案1】:

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

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

    或者这可能有效(将值设置为 null

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

    【讨论】:

      猜你喜欢
      • 2018-05-28
      • 2020-06-10
      • 1970-01-01
      • 2013-01-23
      • 2021-06-14
      • 2020-12-31
      • 2022-08-02
      • 2021-11-17
      • 1970-01-01
      相关资源
      最近更新 更多