下面的代码中db.createCollection会不会build立一个新的数据库?

我在Node工作区的server.js文件中有下面这段代码。 我的问题是,每次我从bash命令行运行我的server.js文件,我是否设置了一个名为polls的新集合? 或者MongoDb认识到集合已经存在? 什么时候我终止我的连接到Mongo,然后从命令行重新启动它?

mongo.connect('mongodb://localhost:27017/url-shortener', function(err, newDb){ if(err){ throw new Error('Database failed to connect'); }else{ console.log('Successfully connected to MongoDb database'); } db = newDb; db.createCollection('polls', { autoIndexId: true }); }); 

db.createCollection有一个名为strict的选项,默认为false ,如果集合已经存在,将会返回错误对象。 修改现有的代码来检查是否存在名称为polls的集合,如果它已经存在,则抛出一个错误。

 mongo.connect('mongodb://localhost:27017/url-shortener', function(err, newDb){ if(err){ throw new Error('Database failed to connect'); } else{ console.log('Successfully connected to MongoDb database'); } db = newDb; db.createCollection('polls', { autoIndexId: true, strict: true }, function(err, collection) { if(err) { //handle error case } }); }); 

有关更多信息,请参阅此链接中的mongodb nodejs驱动程序文档