'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);
    };
});


Solution 1:[1]

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
    };

Solution 2:[2]

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);

Solution 3:[3]

You achieve the desired result by the following code. Hope this will helps you a lot..

var async = require('async');

// custom imports
var User = require('../models/user');
var Article = require('../models/article');

var List1Objects = User.find({});
var List2Objects = Article.find({});
var resourcesStack = {
    usersList: List1Objects.exec.bind(List1Objects),
    articlesList: List2Objects.exec.bind(List2Objects),
};

async.parallel(resourcesStack, function (error, resultSet){
    if (error) {
        res.status(500).send(error);
        return;
    }
    res.render('home', resultSet);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Smbat Poghosyan
Solution 2 Suleyman Celik
Solution 3 Surender Singh