Just as with the MongoDB shell, there is not an explicit method for creating databases. Databases are created automatically whenever a collection or document is added to them. Therefore, to create a new database, all you need to do is use the db()
method on the Db
object provided by the MongoClient
connection to create a new Db
object instance. Then you call createCollection()
on the new Db
object instance to create the database.
The following code shows an example of creating a new database named newDB
after connecting to the server:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/", function(err, db) {
var newDB = db.db("newDB");
newDB.createCollection("newColleciton", function(err, collection){
if(!err){
console.log("New Database and Collection Created");
}
});
});