Node.js 检索集合时出现MongoDB错误

Node.js 检索集合时出现MongoDB错误,node.js,mongodb,Node.js,Mongodb,我在Node.js应用程序中从数据库获取集合时遇到问题。我使用的是MongoDB3.6 我就是这样设置的: var moment = require('moment'); var MongoClient = require('mongodb').MongoClient; /* ===========================================================================

我在Node.js应用程序中从数据库获取集合时遇到问题。我使用的是MongoDB3.6

我就是这样设置的:

var moment                  = require('moment');
var MongoClient             = require('mongodb').MongoClient;

/*
  ===========================================================================
                DB setup
  ===========================================================================
*/


var state = {
  db: null,
}

function get() {
    return state.db;
}

exports.connect_database = function(done) {
    if (state.db) return done()
    MongoClient.connect(process.env.DATABASE_URL, function(err, db) {
        if (err) return done(err)
        state.db = db
        done()
    })
}
/* some other functions ... */

exports.return_collection = function(collection_name, callback) {
    var result_array = [];
    var collection = get().getCollection(collection_name);

    var result = collection.find()
    result.forEach(function(res) {
        result_array.push(res);
    }, function(error) {
        console.log("error: ")
        console.log(error);
        if (!error)
            callback(result_array);
    });
}
在主文件中,我执行以下操作:

'use strict';

// LIB IMPORTS
var env                     = require('node-env-file');
env(__dirname + '/.env');

// LOCAL IMPORTS
var aux                     = require('./modules/aux.js');
var scheduler               = require('./modules/scheduler.js');
var Bot                     = require('./modules/bot.js');

/*
  ===========================================================================
                DB setup
  ===========================================================================
*/

aux.connect_database((err) => {
    if (err) {
        console.log('Unable to connect to Mongo.')
        process.exit(1)
    } else {
        console.log('Connected to db.');
    }
})
我可以在日志中看到连接到db的
提示符,因此连接工作正常。之后,我尝试调用某个函数来添加/检索数据库中的数据,结果出现错误:

TypeError: get(...).getCollection is not a function
    at Object.exports.return_collection
如果我尝试打印state.db变量,会得到以下结果:

MongoClient {
  domain: null,
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  s:
   { url: 'mongodb://localhost:27017/BotDb',
     options:
      { socketOptions: {},
        read_preference_tags: null,
        readPreference: [Object],
        dbName: 'slackBotDb',
        servers: [Object],
        server_options: [Object],
        db_options: [Object],
        rs_options: [Object],
        mongos_options: [Object],
        socketTimeoutMS: 360000,
        connectTimeoutMS: 30000,
        promiseLibrary: [Function: Promise] },
     promiseLibrary: [Function: Promise],
     dbCache: {},
     sessions: [] },
  topology:
   Server {
     domain: null,
     _events:
      { serverOpening: [Function],
        serverDescriptionChanged: [Function],
        serverHeartbeatStarted: [Function],
        serverHeartbeatSucceeded: [Function],
        serverHeartbeatFailed: [Function],
        serverClosed: [Function],
        topologyOpening: [Function],
        topologyClosed: [Function],
        topologyDescriptionChanged: [Function],
        joined: [Function],
        left: [Function],
        ping: [Function],
        ha: [Function],
        authenticated: [Function],
        error: [Function],
        timeout: [Function],
        close: [Function],
        parseError: [Function],
        open: [Object],
        fullsetup: [Object],
        all: [Object],
        reconnect: [Function] },
     _eventsCount: 22,
     _maxListeners: undefined,
     clientInfo:
      { driver: [Object],
        os: [Object],
        platform: 'Node.js v7.10.0, LE' },
     s:
      { coreTopology: [Object],
        sCapabilities: null,
        clonedOptions: [Object],
        reconnect: true,
        emitError: true,
        poolSize: 5,
        storeOptions: [Object],
        store: [Object],
        host: 'localhost',
        port: 27017,
        options: [Object],
        sessionPool: [Object],
        promiseLibrary: [Function: Promise] } } }
我错过了什么?在mongo控制台中,一切看起来都很好:

> db.getCollection("users");
BotDb.users

在Node.js MongoDB本机驱动程序的中找不到任何名为
getCollection
的函数。集合通常是通过以下方式获取的。所以你可以重写这一行:

var collection = get().getCollection(collection_name);

请注意,如果使用v3.0或更高版本的驱动程序,则还必须修改connect函数。对连接函数进行了一些更改(请参阅)。回调现在返回一个客户机对象,而不是db对象。因此,您必须将函数更改为:

exports.connect_database = function(done) {
    if (state.db) return done()
    MongoClient.connect(process.env.DATABASE_URL, function(err, client) {
        if (err) return done(err);
        state.db = client.db('database_name');
        done();
    })
}

请注意
“数据库名称”
字符串。它应该是您数据库的名称。

就是这样,我升级了Mongo v3.0,但没有正确导入客户端数据库!谢谢
exports.connect_database = function(done) {
    if (state.db) return done()
    MongoClient.connect(process.env.DATABASE_URL, function(err, client) {
        if (err) return done(err);
        state.db = client.db('database_name');
        done();
    })
}