如何使用Node JS驱动程序创build新的MongoDb数据库

我想要使​​用Node JS驱动程序在MongoDB中创build一个新的数据库。 我尝试了下面的方法,但他们都没有创build任何数据库(我使用mongo shell和RoboMongo检查),最糟糕的是,它没有显示任何错误,下面的程序成功执行没有任何错误(我的意思是错误是空值)

  • 第一种方法,使用Mongo Server
var Db = require('mongodb').Db, Server = require('mongodb').Server; var db = new Db('myNewDatabase', new Server('localhost', 27017)); db.open(function (err, db) { if (err) { console.dir('ERROR we are in the callback of the open '); console.dir(err); throw err; } // Use the admin database for the operation var adminDb = db.admin(); console.dir('we are in the callback of the open'); db.close(); }); 

  • 我遵循的第二种方法是:
 var server = "localhost"; var port = 27017; var dbName = "myNewDatabase"; var mongodb = require('mongodb'); var mongoClient = mongodb.MongoClient; var connString = "mongodb://"+server+":"+port+"/"+dbName; mongoClient.connect(connString, function(err, db) { console.dir(err); if(!err) { console.log("\nMongo DB connected\n"); db.collection('test_correctly_access_collections', function(err, col2) { console.dir(err); if(err) { console.dir('Thier is a error in creating collection'); console.dir(err); } console.log("\nColllection created succesfully\n"); db.close(); }); } else{ console.log("Mongo DB could not be connected"); process.exit(0); } }); 

根据这个链接 ,我们可以使用getDatabase API来创build一个新的数据库,我尝试了Node JS中的同一个API,但是我找不到一个。

在谷歌和stackOverflowsearch这个问题,但我能find,只有非常less的。 所以我自己发布这个答案。

起初谢谢@somallg,你是对的,我把你的评论投了。

答案是,您需要将文档插入到集合中,然后,MongoDB将创build新的数据库以及集合。 所以,在我的问题上面的方法,我们可以重写如下使用节点JS驱动程序创build一个新的数据库:

  • 首先Appoarch
 var Db = require('mongodb').Db, Server = require('mongodb').Server; var db = new Db('myNewDatabase', new Server('localhost', 27017)); db.open(function (err, db) { if (err) { console.dir('ERROR we are in the callback of the open '); console.dir(err); throw err; } var collection = db.collection("simple_document_insert_collection_no_safe"); collection.insert({hello:'world_no_safe'}); console.dir('we are in the callback of the open'); db.close(); });