I'm new programming in Node and I'm stuck because I no understand exactly what is the difference between .find and .exec. Here is the code that I'm trying to run:
exports.getPopulatedUsers = async function(query){
var res = await users.find(query, function (err, docs) {
if(err) return err;
return docs;
});
return res; // **Work fine, res return docs**
}
But when execute with .exec the res is undefined.
exports.getPopulatedUsers = async function(query){
var res = await users.find(query).exec(function (err, docs) {
if(err) return err;
return docs;
});
return res; // **ERROR, res is undefined **
}
What am I doing wrong?
find() and exec() serve two different purposes.
The find() method is a database READ operation enabling function. It is
present in both the native mongodb driver for node, as well as the Mongoose library which internally uses the mongodb drivers and is especially useful for imposing a fixed schema.
Now, in mongodb driver, if you use find(query)
, the query is automatically executed where as in mongoose it wouldn't. We need helper functions/ callbacks to get the operation to execute.
exec is one such helper function.
It goes something like: myPlaylist.findOne({'singer':'Adam Levine'}).exec()
Mongoose queries are not promises. They have a .then() function for convenience.
If you need a fully-fledged promise, use the .exec() function.
So, you could do a myPlaylist.findOne({'singer':'Adam Levine'}).then()
but that would return a Mongoose/BlueBird (yet another library) promise and a typical JavaScript one.
Note: exec() takes an optional callback function. It's only when you do not use a callback that you get back a Promise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With