【问题标题】:MongoDB returning an onject that doesnt existMongoDB 返回一个不存在的对象
【发布时间】:2025-12-03 16:35:01
【问题描述】:

我正在使用 MongoDB 和护照做一个项目,当我遇到这个错误时,虽然 p1 没有被使用,但它仍然重新运行我猜测的对象,因为它只是说字段 p1 被占用,当它不是。 p2也是如此。有谁知道为什么?

passport.use(
  "local.signup",
  new LocalStrtegy(
    {
      usernameField: "email",
      passwordField: "password",
      passReqToCallback: true,
    },
    async function (req, email, password, done) {
      req.checkBody("email", "E-mail is empty").notEmpty();
      req
        .checkBody("password", "Your password is too short!")
        .isLength({ min: 4 });
      var errors = await req.validationErrors();
      if (errors) {
        var messages = [];
        errors.forEach(function (error) {
          messages.push(error.msg);
        });
        return done(null, false, req.flash("error", messages));
      }
      const p1 = User.find({ p1: req.body.p1 });
      const p2 = User.find({ p2: req.body.p2 });

      User.findOne({ email: email }, function (err, user) {
        if (err) {
          return done(err);
        }

        if (user) {
          return done(null, false, {
            message:
              "This E-Mail alredy in use! If you believe that this is an error, please an admin on. (ERR 002 MCEE)",
          });
        } else if (p1) {
          return done(null, false, {
            message:
              "This username is alredy in use! If you believe that this is an error, please contact an admin. (ERR 002 MCEM)",
          });
        } else if (p2) {
          return done(null, false, {
            message:
              "This Tag is alredy in use! If you believe that this is an error, please contact an admin. (ERR 002 MCED)",
          });
        }

        console.log(mc + " " + dcign + " " + user);
        var newUser = new User();
        newUser.email = email;
        newUser.password = newUser.encryptPassword(req.body.password);
        newUser.p1 = req.body.p1;
        newUser.p2 = req.body.p2;
        newUser.Banned = false;
        console.log(req.body);
        newUser.save(function (err, result) {
          if (err) {
            return done(err);
          }
          return done(null, newUser);
        });
      });
    }
  )
);

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    调用 User.find 会返回一个你没有等待的 Promise。因此,当您检查 p1 和 p2 是否存在时,它会返回一个真值,因为这两个值都是 Promise 对象。

    要解决这个问题,请在 User.find 前面使用 await,就像这样

    const p1 = await User.find({ p1: req.body.p1 });
    const p2 = await User.find({ p2: req.body.p2 });
    

    之后,当您使用 find 方法时,这两个值都将是数组,因此只需检查长度属性或更好地使用 findOne 而不是 find 方法。

    const p1 = await User.findOne({ p1: req.body.p1 });
    const p2 = await User.findOne({ p2: req.body.p2 });
    

    【讨论】:

      【解决方案2】:
      1. MongoDB .find 返回一个数组。在您的情况下, p1 是一个空数组。 if(p1) 将始终返回 true。你应该检查它的长度。
      2. 您应该使用await 进行查询调用。
        const p1 = await User.find({ p1: req.body.p1 });
        const p2 = await User.find({ p2: req.body.p2 });
        

      我在下面粘贴示例代码 -

      passport.use(
        "local.signup",
        new LocalStrtegy(
          {
            usernameField: "email",
            passwordField: "password",
            passReqToCallback: true,
          },
          async function (req, email, password, done) {
            req.checkBody("email", "E-mail is empty").notEmpty();
            req
              .checkBody("password", "Your password is too short!")
              .isLength({ min: 4 });
            var errors = await req.validationErrors();
            if (errors) {
              var messages = [];
              errors.forEach(function (error) {
                messages.push(error.msg);
              });
              return done(null, false, req.flash("error", messages));
            }
            const p1 = await User.find({ p1: req.body.p1 });
            const p2 = await User.find({ p2: req.body.p2 });
      
            User.findOne({ email: email }, function (err, user) {
              if (err) {
                return done(err);
              }
      
              if (user) {
                return done(null, false, {
                  message:
                    "This E-Mail alredy in use! If you believe that this is an error, please an admin on. (ERR 002 MCEE)",
                });
              } else if (p1.length) { // Check for Length
                return done(null, false, {
                  message:
                    "This username is alredy in use! If you believe that this is an error, please contact an admin. (ERR 002 MCEM)",
                });
              } else if (p2.length) { // Check for Length
                return done(null, false, {
                  message:
                    "This Tag is alredy in use! If you believe that this is an error, please contact an admin. (ERR 002 MCED)",
                });
              }
      
              console.log(mc + " " + dcign + " " + user);
              var newUser = new User();
              newUser.email = email;
              newUser.password = newUser.encryptPassword(req.body.password);
              newUser.p1 = req.body.p1;
              newUser.p2 = req.body.p2;
              newUser.Banned = false;
              console.log(req.body);
              newUser.save(function (err, result) {
                if (err) {
                  return done(err);
                }
                return done(null, newUser);
              });
            });
          }
        )
      );
      

      【讨论】:

        最近更新 更多