Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return results mongoose in find query to a variable

I need to return the results of a query with mongoose in node.js.

How do you return the value to set the value to a variable?

What I need to do is:

var results = users.findOne({_id : users_list[i]['user_id']},{email : 1, credits : 1},{}, function(err, docs) {
    if( err || !docs) {
        console.log("No user found");
    } else {            
        return docs;
    };
});

In order to have:

results = docs 

Thanks a lot for your reply .

I also have another problem.

How to pass variable in a query operator with find or findOne? Like :

var foo = "Blaa";

users.findOne({_id : users_list[i]['user_id']},{email : 1, credits : 1},{}, function(err, docs) {
    if( err || !docs) {
        console.log("No user found");
    } else {
        // I want to use the foo variable here
        console.log(foo);
    };
});
like image 813
Xanarus Avatar asked Jun 04 '14 11:06

Xanarus


People also ask

What does find () return in mongoose?

find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries.

Does find return an array mongoose?

find returns an array always.

What is $in in mongoose?

The value of the $in operator is an array that contains few values. The document will be matched where the value of the breed field matches any one of the values inside the array.

How do you use mongoose findOne?

Mongoose | findOne() FunctionThe findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition. Installation of mongoose module: You can visit the link to Install mongoose module.


3 Answers

There are several ways to achieve what you want.

1. Using Mongoose Queries

In this strategy, your function returns a Mongoose query which you can later use to invoke the method exec and use it to get the results.

function getJedisQuery(name){    var query = Jedi.find({name:name});    return query; } 

Then you can use it simply doing:

var query =  getJedisQuery('Obi-wan'); query.exec(function(err,jedis){    if(err)       return console.log(err);    jedis.forEach(function(jedi){       console.log(jedi.name);    }); }); 

2. Using Mongoose Promise-like Objects

Moogose provides support for promise-like objects. All you have to do is something somewhat similar to what I did above, but this time, you invoke the exec method without a callback.

function getJedisPromise(name){    var promise = Jedi.find({name:name}).exec();    return promise; } 

Then you can use it by simply doing:

var promise = getJedisPromise('Luke'); promise.then(function(jedis){    jedis.forEach(function(jedi){       console.log(jedi.name);    }); }) 

As highlighted in the comment section of this answer, these objects are not in fact promises and that needs to be taken into account (see Queries are not promises).

3. Using Mongoose Streams

Finally, Mongoose has also support for streams and streams are event emitters. So, you could get a stream and then subscribe for 'data' and 'error' events. Like this:

function getjedisStream(name){    var stream = Jedi.find({name:name}).stream();    return stream; } 

Then you can simply do:

var stream = getJedisStream('Anakin'); stream.on('data', function(jedis){    jedis.forEach(function(jedi){       console.log(jedi.name);    }); }); stream.on('error', function(error){     console.log(error); }); 

Source, for future reference.

like image 146
Edwin Dalorzo Avatar answered Oct 11 '22 05:10

Edwin Dalorzo


It is being executed before the assignment.

 async function(req, res) {       var user;       await users.findOne({}, function(err,pro){           user=pro;         });       console.log(user); \\ it's define     }; 
like image 29
Javad.mrz Avatar answered Oct 11 '22 05:10

Javad.mrz


You can easily achieve this.

const getUser = async ( req, res ) => {
   let users = () => ( User.find({_id : users_list[i]['user_id']},{email : 1, credits : 1}).exec() );

   try { res.send({"user":await users() });}
   catch(e) { console.log(e) } 
}

app.get('/user' , getUser);
like image 24
Kavale arun Avatar answered Oct 11 '22 05:10

Kavale arun