0

Iam beginner, first i installed npm install mongodb, then i create js file as demo_create_mongo_db.js

I used following code to create database

var MongoClient = require('mongodb').MongoClient;
//Create a database named "mydb":
var url = "mongodb://localhost:27017/mydb";

 MongoClient.connect(url, function(err, db) {
 if (err) throw err;
 console.log("Database created!");
 db.close();
 });

then i just run node demo_create_mongo_db.js following error occured

this error found

Why this error occur? how can i handle this?

Thanks

2
  • 1
    You need to install MongoDB database in your system and run mongod server to listen to any mongodb request on port 27017. In a separate terminal run mongod.exe also Commented Oct 21, 2017 at 9:36
  • Your question is how to create db or connect to DB? Commented Sep 30, 2019 at 13:32

3 Answers 3

1

index.js

At first, install MongoDB module by running this command.

npm install mongodb --save

Just keep in mind that you can not create the only database. You have to create also the collection to see your new database.

const mongodb = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new mongodb.MongoClient(uri);

client.connect((err) => {
    if (!err) {
        console.log('connection created');
    }
    const newDB = client.db("YourNewDatabase");
    newDB.createCollection("YourCreatedCollectionName"); // This line i s important. Unless you create collection you can not see your database in mongodb .

})

Now run this index file by the following command in your terminal

node index.js

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Mongoose library to connect to MongoDB in Node JS

 var mongoose = require('mongoose');
 mongoose.connect('mongodb://localhost:27017/'+db_to_connect,{ useNewUrlParser: true });

 var db = mongoose.connection;
 db.on('error', function(){             
 });
 db.once('open', ()=> {
 });

Comments

0

Seem your mongo server havn't runing yet!! run mongo in comment line to check if mongo server is runing or not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.