下面代码中的 db.createCollection 是否总是会建立一个新的数据库?

ran*_*101 3 bash mongodb node.js

我的 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
    });
});
Run Code Online (Sandbox Code Playgroud)

Ana*_*Pai 5

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
       }
    });
});
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您可以参考此链接的 mongodb Nodejs 驱动程序文档