Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MongoDB with promises in Node.js?

I've been trying to discover how to use MongoDB with Node.js and in the docs it seems the suggested way is to use callbacks. Now, I know that it is just a matter of preference, but I really prefer using promises.

The problem is that I didn't find how to use them with MongoDB. Indeed, I've tried the following:

var MongoClient = require('mongodb').MongoClient;  var url = 'mongodb://localhost:27017/example';  MongoClient.connect(url).then(function (err, db) {     console.log(db); }); 

And the result is undefined. In that case it seems this is not the way to do so.

Is there any way to use mongo db inside Node with promises instead of callbacks?

like image 372
user1620696 Avatar asked Jun 19 '16 21:06

user1620696


People also ask

How do I use promises in Node JS?

A custom promise can be created by using a node module called 'q. ' The 'q' library needs to be downloaded and installed using the node package manager. After using the 'q' library, the method “denodeify” can be called which will cause any function to become a function which returns a promise.

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.

Can we use MongoDB with Node js?

The MongoDB Node. js Driver allows you to easily interact with MongoDB databases from within Node. js applications. You'll need the driver in order to connect to your database and execute the queries described in this Quick Start series.

How do you use promises instead of callbacks?

Promises are JavaScript objects that represent an eventual completion or failure of an asynchronous operation. A promise is a returned object where you attach callbacks, instead of passing callbacks into a function. the place where you attach the callback after a successful completion of a task is called, . then().


1 Answers

Your approach is almost correct, just a tiny mistake in your argument

var MongoClient = require('mongodb').MongoClient var url = 'mongodb://localhost:27017/example' MongoClient.connect(url)   .then(function (db) { // <- db as first argument     console.log(db)   })   .catch(function (err) {}) 
like image 187
Green Avatar answered Sep 28 '22 11:09

Green