Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose find vs exec. How to return values?

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?

like image 827
Bell Mundarain Avatar asked Mar 05 '23 23:03

Bell Mundarain


1 Answers

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.

like image 173
Sushmita Mallick Avatar answered Mar 15 '23 04:03

Sushmita Mallick