Nirmal kumar
Nirmal kumar

Reputation: 65

How to create database in Mongodb using Node js?

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

Upvotes: 0

Views: 2074

Answers (3)

Sakthikanth
Sakthikanth

Reputation: 139

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', ()=> {
 });

Upvotes: 1

Ahmad Sharif
Ahmad Sharif

Reputation: 4435

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

Upvotes: 1

Le Dinh Dam
Le Dinh Dam

Reputation: 122

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

Upvotes: 0

Related Questions