1

I want to query last 10 elements in Mongodb and return elements in this query for render to index.ejs I try a lot of way for this for example (callback,asyc function) but I can't fix this problem

function getlastelements(ID){
var MongoC = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/Weatherdb';
MongoC.connect(url, function(err,db){    
    var collection = db.collection('datas');  
    collection.find({"ID" : String(ID)}).sort({_id:-1}).limit(10),(function(err,cursor){
      var xyz = cursor.toArray();
      return(xyz.length);

     })    
});
}
console.log(getlastelements(1));
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Aug 27 '17 at 20:52
  • So, In this situation my function is an asynchronous call. Am I right? – YlmzCmlttn_Old Aug 27 '17 at 21:02

1 Answers1

1

Your function can return a promise on which you can call the .then() method to get the value (also, remember to close the db at the end of the function)

var mongodb = require('mongodb')
function getlastelements(ID){
    return new Promise(function(resolve, reject){
            var MongoC = mongodb.MongoClient;
            var url = 'mongodb://localhost:27017/Weatherdb';
            MongoC.connect(url, function(err,db){
             var collection = db.collection('datas');
             collection.find({"ID" : String(ID)}).sort({_id:-1}).limit(10)
            .toArray(function(err, cursor){
                            if(err) reject(err)
                            resolve(cursor.length)
                            db.close()
                    })
            })
    });
}
getlastelements(1).then(result => console.log(result)).catch(err => console.log(err)

Javascript Promises

doze
  • 287
  • 2
  • 13