0

How can i save a variable from async function .find from mongodb? Inside the function console.log its working (prints the right value) and outside the function it is undefined.

var list;
MongoClient.connect(uri, function(err, db) {
    var dbc = db.db("chat");
    dbc.collection("chat_messages").find({user1: data.from, user2: data.to}).toArray(function (err, result){
         console.log(result[0].msgs);    <---- here its working
                
         list = result[0].msgs;
    });
            
    db.close();
});
console.log(list);     <---- here its not working

3 Answers3

0

Here's how you would do it with async await.

async function getList() {
let db = await MongoClient.connect(url);
let dbo = db.db("testdb");
return await dbo.collection("cars").find({}, { projection: { _id: 0, name: 1} }).toArray()
}
        
listCars().then(cars => {
console.log(cars); //You will get your results here
})

The mongoDB queries in nodejs like the one above are asynchronous so you cannot get the return value in a variable directly. You either have to use a callback function or .then() to use promises like in the example above.

The toArray() function you are using is a MongoDB method, the one you mentioned in your question is a jQuery one. This is the correct documentation for your reference -> https://docs.mongodb.com/manual/reference/method/cursor.toArray/

Nimra Haider
  • 119
  • 3
  • 11
0

You need to make the entire code block into an async-await code block, or take in the help of then block

let conn = await client.connect(url);
let db = conn.db("test");
const results =  await db.collection("cars").find({}, { projection: { _id: 0, name: 1} }).toArray()

here results will have your output

HexaCrop
  • 3,863
  • 2
  • 23
  • 50
0

try work with Promises, look that sample:

const list = new Promise(function (resolve, reject) {
  MongoClient.connect(uri, function(err, db) {
    var dbc = db.db("chat");
    dbc.collection("chat_messages").find({user1: data.from, user2: data.to}).toArray(function (err, result){
         if(err) {
             reject(err);
         } else {
             resolve(result);         
         }
         db.close();
    });   
  });
});

Then use as promise if you need:

list.then(arrayList => {
  console.log(arrayList[0].msgs);
}).catch(err => console.log(err.message));

OR, force to run sync

const msgs = (await list)[0].msgs;
Marcus Yoda
  • 243
  • 1
  • 8