G2code
G2code

Reputation: 51

How to retrieve value from mongodb with await function?

I want to write a function which pass query and url and retrieve values from mongodb. The values must be used outside the function. How to write an await function?

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {  
  if (err) throw err;  

  var x = "1001"

  var query = ({
    "land_id": x
  }); 

  var dbo = db.db("deed");
  dbo.collection("deedusers").find(query).toArray(function(err, result) {  
    if (err) throw err;  
    else if(result.length >0)
      console.log(result);  

    var name = result[0].name;
    var email = result[0].email

    console.log(name);
    console.log(email);   

  });  
}); 

I can print name and email but cant use it outside the function. I want to use variable name and email outside the function.

Upvotes: 1

Views: 328

Answers (1)

Faiz Khan
Faiz Khan

Reputation: 298

You can do this:

var myFunc = async function(query) {
  var db;
  var client;
  try {
    client = await MongoClient.connect(connection string, { useNewUrlParser: true });
    db = client.db(DatabaseName);
    return await db.collection(collectionName).find(query).toArray();
  } finally {
    client.close();
  }
}

Now you can call myFunc and then get the results from the query

myFunc(query).then(res => {
  console.log(res)
})

you can also do this:

let result = myFunc(query)
result.then(res =>{
//Do something with res and then return the modified value it will pass this value in next .then
 return modifiedres
}).then(ans =>{
//Here you can again do something and return it and it will pass in next .then or do whatever you want and in last use .catch
}).catch(error =>{
 console.log(error)
})

Upvotes: 4

Related Questions