smus
smus

Reputation: 143

Can't connect to a MongoDB using Node.js

Can't connect to a MongoDB using Node.js.

This is my code (mdb.js):

var MongoClient = require('mongodb').MongoClient, format = require('util').format;

MongoClient.connect('mongodb://localhost:3000', function(err,db){

    if(err){
         throw err;
    } else {
         console.log("Connected");
    }
    db.close();
});

node mdb.js prints MongoError:

enter image description here

Upvotes: 3

Views: 14055

Answers (4)

user18462442
user18462442

Reputation:

First of all please verify that have you changed your default database port from 27017 to 3000 or not. If not changed then please try the below code it's working for me

 const { MongoClient } = require("MongoDB");

 // Connection URL
 const url = "mongodb://localhost:27017";
 const client = new MongoClient(URL);

 // Database Name
 const dbName = "myProject";

 async function main() {
    // Use connect method to connect to the server
    await client.connect();
    console.log("Connected successfully to server");
    const db = client.db(dbName);
    const collection = db.collection("documents");

    // return "done.";
 }

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close());

Also here is I attached a my screenshot with the output Sample output example

Upvotes: 0

psycho
psycho

Reputation: 1

Use this URL mongodb://0.0.0.0:3000

Upvotes: 0

tridio
tridio

Reputation: 171

it worked for me when i changed 'localhost' to 127.0.0.1

Upvotes: 16

Mykola Borysyuk
Mykola Borysyuk

Reputation: 3411

Your error explaining itself. Mongo cant find default db path B:/data/db.

Create this folder or on start up choose another DB directory

mongod --dbpath yourPath(C:\myDb)

Also default mongo port is 27017 so you need to change connection string like this "mongodb://@localhost:27017/dbYouWant"

Hope this helps.

Upvotes: 1

Related Questions