Node Express Mongodb连接语法和错误处理

时间:2017-10-03 04:18:22

标签: node.js mongodb express

我的应用中出现了一个问题,就是我对我提供给mongodb连接的数据库名称的疏忽。在环顾四周的时候,我遇到了这些例子:

https://wesleytsai.io/2015/08/02/mongodb-connection-pooling-in-nodejs/

所以我的问题是,如果我提供mongodb连接不存在的数据库,为什么我不会抛出任何错误?我只需要帮助解释/理解下面的语法。在这一行:

MongoClient.connect(mongoUrl, function(err, database) { 
    if( err ) throw err;
.
.
.
不应该抛出错误,因为如果数据库不存在,mongo就无法连接?

我尝试做的是设置某种错误处理方式,可以标记数据库不存在的事实,如果不存在,也可以标记该系列('费用& #39;应该测试')。

var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var mongoUrl = 'mongodb://127.0.0.1:27017/expenses';
var db;

exports.connect = function(callback) {
  MongoClient.connect(mongoUrl, function(err, database) {
    if( err ) throw err;
    db = database;
    callback();
  })
}

1 个答案:

答案 0 :(得分:0)

在mongodb中,如果您连接到数据库,然后为您定义的集合提供模式,那么无论该集合是否存在,mongodb都会为您创建集合。

例如,如果您有以下代码,

module.exports = mongoose.model('User', schema);

在数据库中创建名为users的集合。所以即使你没有收藏品,mongodb也会为你创造一个。

如果要检查数据库是否存在,请按以下步骤操作:

var mongoose = require('mongoose')
    , Admin = mongoose.mongo.Admin;

/// create a connection to ypur database
var connection = mongoose.createConnection(
    'mongodb://user:password@localhost:port/your_database');
connection.on('open', function() {
    // connection successful
    new Admin(connection.db).listDatabases(function(err, result) {
        console.log('listDatabases successful');
        // the database lists are stored in result.databases
        var allDatabases = result.databases; 
        // allDatabases contains the record of all the databases
        // crosscheck this list with the database you want 
    });
});
相关问题