Miguel Lorenzo
Miguel Lorenzo

Reputation: 560

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.

Upvotes: 0

Views: 1761

Answers (2)

red
red

Reputation: 3233

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');

});

Upvotes: 3

robertklep
robertklep

Reputation: 203419

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.

Upvotes: 0

Related Questions