WinchenzoMagnifico
WinchenzoMagnifico

Reputation: 3425

what is the benefit to using mongoose .exec?

  User.find().exec(function (err, users) {
    if (err){
      callback(err);
    } else {
      callback(users);
    }
  });


  User.find(function (err, users) {
    if (err) {
      callback (err);
    } else {
      callback(users);
    }
  });

What is the benefit of using the top code? both seem to work equally well

Upvotes: 3

Views: 401

Answers (1)

Molda
Molda

Reputation: 5704

They are identical and there's no benefit in your example

When you do not pass a callback to find function it won't execute but instead returns a query then you need to use exec()

var query = User.find();

now you can add some more criteria

query.where({age: 15});

and some more

query.select({name:1}); // or {firstname:1, lastname:1} etc.

now you've built up your query so to get the results you need to execute it.

query.exec(function(err, users){

});

But you can also do this like

User.find({age:15}, {name:1}, function(err, users){

});

Above is identical to

User.find({age:15}, {name:1}).exec(function(err, users){

});

since there's no callback in find function it will return query which means no results, exec will give you the results

Upvotes: 4

Related Questions