Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I came across a piece of Mongoose code that included a query findOne and then an exec() function.

I've never seen that method in Javascript before? What does it do exactly?

2 Answers

0 votes
by (106k points)

To understand the exec function basically when using mongoose, documents can be retrieved using helpers. Every model method that accepts query conditions can be executed by means of a callback or the exec method.

callback:

User.findOne({ name: 'daniel' }, function (err, user) { 

// 

});

exec:

User .findOne({ name: 'daniel' }) .exec(function (err, user) { // 

});

0 votes
by (107k points)

The following design is very handy and generic - it can handle callbacks or promises accurately:

function findAll(query, populate, cb) {

  let q = Response.find(query);

  if (populate && populate.length > 0) {

    q = q.populate(populate);

  }

  // cb is optional and it will return promise if cb == null

  return q.lean().exec(cb);

}

Related questions

0 votes
2 answers
0 votes
2 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...