我在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
});
});发布于 2016-09-13 19:35:59
db.createCollection有一个名为strict的选项,默认情况下为false,如果集合已存在,则该选项在设置为true时将返回错误对象。修改现有代码,检查名为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
}
});
});有关更多信息,您可以在this链接上参考mongodb nodejs驱动程序文档
https://stackoverflow.com/questions/39466444
复制相似问题