Reputation: 143
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:
Upvotes: 3
Views: 14055
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
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