Using native ES6 promises with MongoDB

I know that the Node driver for Mongo can promisified use external libraries. I was curious to see if ES6 promises can be used with MongoClient.connect , so I tried this (using Babel 5.8.23 for forwarding):

 import MongoClient from 'mongodb'; function DbConnection({ host = 'localhost', port = 27017, database = 'foo' }) { return new Promise((resolve, reject) => { MongoClient.connect(`mongodb://${host}:${port}/${database}`, (err, db) => { err ? reject(err) : resolve(db); }); }); } DbConnection({}).then( db => { let cursor = db.collection('bar').find(); console.log(cursor.count()); }, err => { console.log(err); } ); 

Output signal {Promise <pending>} . Everything related to cursors seems to give a similar result. Is there any way around this, or am I completely barking on the wrong tree?

Edit: Node version 4.1.0.

+6
source share
2 answers

Nothing to get around, this is the expected behavior. cursor.count() returns a promise, if you need a value, you need to use .then , for example.

 DbConnection({}).then( db => { let cursor = db.collection('bar').find(); return cursor.count(); } }).then( count => { console.log(count); }, err => { console.log(err); } ); 

or simplified

 DbConnection({}).then(db => db.collection('bar').find().count()).then( count => console.log(count), err => console.log(err) ); 
+10
source

Another loganfsmyth response syntax (thanks, by the way)

 cursor.count().then(function(cursor_count){ if(cursor_count){ // use cursor }else{ // no results } } 
0
source

All Articles