Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)
recategorized by

I want to use MongoDB with Node.js and in the official documents it is suggesting to use callbacks. Now, I know that it is just a matter of preference, but I really prefer using promises.

I have 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.

Can you help me?

1 Answer

0 votes
by (107k points)
edited by

The approach that you are implementing is correct but there is only one mistake that you have done in the argument. Refer the following code:

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 are interested in learning MongoDB, then do checkout the MongoDB tutorial that will help you in a better way. 

Want to learn MongoDB from the experts, Check out this MongoDB Training in London to enhance your Knowledge!

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...