YlmzCmlttn YlmzCmlttn - 2 months ago 25
Node.js Question

How to query in MongoDB in function and res.render to ejs

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

Answer Source

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