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?
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.
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.
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.
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().
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) {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With