Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using native ES6 promises with MongoDB

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

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

The output is {Promise <pending>}. Anything to do with cursors seems to yield a similar result. Is there a way to get around this or am I barking up the wrong tree entirely?

Edit: node version 4.1.0.

like image 485
Rich Churcher Avatar asked Sep 25 '15 23:09

Rich Churcher


People also ask

Can JavaScript connect to MongoDB?

The MongoDB JavaScript (NodeJS) Driver makes it simple to work with MongoDB databases from Node. js applications. To connect to your database and run the queries discussed in this Quick Start series, you'll need the MongoDB JavaScript (NodeJS) driver.

What is Promise in MongoDB?

A Promise is an object returned by the asynchronous method call that allows you to access information on the eventual success or failure of the operation that they wrap.

Is MongoDB asynchronous?

The MongoDB Async driver provides an asynchronous API that can leverage either Netty or Java 7's AsynchronousSocketChannel for fast and non-blocking IO.

Is JavaScript necessary for MongoDB?

Yes, a basic understanding of JavaScript along with familiarity with OOPS concepts is required. The course's title is: “MongoDB for JavaScript Developers” and the objective of this course is to introduce JavaScript Developers to MongoDB and to Learn the essentials of Node.


1 Answers

There is nothing to get around, this is the expected behavior. cursor.count() returns a promise, if you want the value, you need to use .then, e.g.

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)
);
like image 108
loganfsmyth Avatar answered Oct 04 '22 21:10

loganfsmyth