当不存在的东西(即使在空数据库上)时,MongoDB find总是返回true

时间:2018-09-19 18:55:06

标签: node.js database mongodb mongoose nosql

app.post('/sign-up', function (req, res) {
  let emailValid = validator.validate(req.body.email);
  let consent = req.body.consent ? true:false

  if(emailValid && consent) {
    const user = new UserModel({
      name: req.body.firstName,
      surname: req.body.surname,
      email: req.body.email
      })
      UserModel.find({'email': req.body.email}, function(notFound, found) {
        if(notFound) {
          user.save().then(item => {
            console.log('Saved successfully!');
            res.render('submitSuccess', {data: req.body});
          }).catch(err => {
            res.status(400).render('404');
          })
        } else if(found) {
          console.log('Exists');
          res.status(404).render('submitSuccess', {data:req.body});
        }
         else {
          res.status(404).render('404');
        }
      });  
    }
});

此处的预期功能是,如果有人向已存在的数据库提交电子邮件,则它不会保存重复的邮件。但是,似乎Found每次都会返回true,因此什么也得不到保存。

1 个答案:

答案 0 :(得分:1)

运行以下代码:

app.post('/sign-up', function (req, res) {
let emailValid = validator.validate(req.body.email);
let consent = req.body.consent ? true : false

if (emailValid && consent) {
    const user = new UserModel({
        name: req.body.firstName,
        surname: req.body.surname,
        email: req.body.email
    })
    UserModel.find({ 'email': req.body.email }, function (err, found) {
        if (err) {
            console.error(err);
            res.status(500).end();
            return;
        }

        if (found.length == 0) {
            user.save().then(item => {
                console.log('Saved successfully!');
                res.render('submitSuccess', { data: req.body });
            }).catch(err => {
                res.status(400).render('404');
            })
        } else {
            console.log('Exists');
            res.status(404).render('submitSuccess', { data: req.body });
        }
    });
  }
});

err中有什么?