Marina
Marina

Reputation: 31

Reasons why am I struggling to connect node with MongoDB

I am having trouble connecting Node with MongoDB.

I have tested both of them separately and they work fine. I have also created a path for the db. What else could I be missing?

var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }
});

Upvotes: 2

Views: 63

Answers (2)

Nikola Lukic
Nikola Lukic

Reputation: 4246

Try something like this:

 /**
  * Open connection with database.
  */

   MongoClient.connect("exampleDb", { useNewUrlParser: true },    

   function(error, db) {
      if (error) {
          console.warn("MyDatabase : err1:" + error);
          return;
      }

       const dbo = db.db(databaseName);

      // Demo - Use it in usual way.
      // dbo.collection("users").findOne({ "email": email }, function(err, result) { 

      // });

You can find more explanation on :

https://github.com/DefinitelyTyped/DefinitelyTyped/pull/27067

Upvotes: 2

Chicky
Chicky

Reputation: 1257

const MongoClient = require('mongodb').MongoClient;

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

Upvotes: 0

Related Questions