How to return values from Mongoose query

lumberjacked picture lumberjacked · Nov 10, 2013 · Viewed 7.7k times · Source

I am working on a registration piece that does some server side validation before entering the data to mongo. I am very new to mongoose and am having trouble returning data to a method that completes all the registration process.

In my locomotive controller I have a method that wraps everything to start a sign-up process.

auth = new Authenticator();
auth.signUp(this.req.body);

Inside my auth object signUp just runs through validating the data before creating a new user. One validation is that there is not a duplicate email created in the database already.

this.signUpUser = function(user) {

    if(this.isNotDuplicate(user.email) {
       //continue doing whatever needs done to the data afterwards 
    } else {
        response['error'] = True
        response['response'] = "duplicate email"
    }

}

One method I'm trying is looking for an email that matches and returning true or false.

this.isNotDuplicate = function(email) {

    query = user.findOne({ 'email': email });
    query.exec(function(error, user) {

        if(error) {
            console.log(error);
        }

        console.log(user);
        return (user === null) ? false : true;

     });
}

If I pass in an email in the database that is there I can see the user when I use console.log() but this does not allow me to return anything unless it is locomotives return response object. But I need to be able to continue doing processing on the data. I realize I could be doing this just completely wrong so if my design is bad I need an explanation on how to change it to work with node.js, express, and locomotive.

I have read mongoose's documentation on queries (http://mongoosejs.com/docs/queries.html). In their examples they use console.log(), but certainly there is a way to use the data you pull from mongoose elsewhere and not just in the mongoose query. If my design is bad going this route how would it be suggested to change it? Or how can I just return either the data from a mongoose query or another value to use?

Answer

Evan Lucas picture Evan Lucas · Nov 10, 2013

You will need to make this.isNotDuplicate asynchronous. Try something like this:

this.isNotDuplicate = function(email, callback) {
  var query = user.findOne({ 'email': email })
  query.exec(function(err, user) {
    if (err) {
      console.log(err)
      callback(err)
    } else {
      console.log(user)
      cb(null, !!user)
  })
}

And then when checking for the user:

this.signUpUser = function(user) {
  this.isNotDuplicate(user.email, function(err, exists) {
    if (err || exists) {
      response['error'] = true
      response['message'] = (exists) ? 'duplicate email' : 'error'
    } else {
      // continue doing whatever needs to be done
    }
  })
}