Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create database node.js with mongodb

I am able to drop database using node.js but I dont know how to create new database? I want to create monogo database using node.js. Can someone help me about how to create mongo database using node.js?

like image 636
vkt Avatar asked Mar 02 '16 21:03

vkt


1 Answers

At first, install MongoDB module by running this command.

npm install mongodb --save

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

index.js

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

like image 57
Ahmad Sharif Avatar answered Oct 12 '22 11:10

Ahmad Sharif