Back
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?
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) { // });
callback:
User.findOne({ name: 'daniel' }, function (err, user) {
//
});
exec:
User .findOne({ name: 'daniel' }) .exec(function (err, user) { //
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);}
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);
31k questions
32.8k answers
501 comments
693 users