简体   繁体   中英

How to check if an embedded document exists in database before saving in Mongoose

I'm making a basic authentication system using Express, Mongoose and PassportJS. What I want to do is to check the database if the entered username and password already exist in the database. Here's my sample code below:

//Post: /signup
app.post('/signup', function (req, res) {
  var username = req.body.person.user.username;
  var password = req.body.person.user.password;

  Person.user.find({'username': username}, function (err, user) {
    if (err) {
      console.log(err.name);
    } else {
      console.log('User Found');
    }
  });
});

The problem is it returns this kind of error:

TypeError: Cannot call method 'find' of undefined

Could someone please help me.

As robertklep pointed, you are not checking correctly for an user's existence. Also, since username is most likely unique, you can just use findOne (findOne() returns a single object while find() may also return a single object but will wrap it in an array).

Person.findOne({'username': username}, function (err, user) {
  if (err) {
     console.log(err.name);
     return;
  }
  if (!user)
    console.log('User not Found');
    return;
  }
  console.log('User found');

});

I think you're looking for this:

Person.find({ 'user.username' : username }, ...)

FWIW, if the callback isn't called with an error it doesn't mean a user was found, it just means that there were no errors performing the query. But user can still be null, meaning that the query didn't have any matching results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM