簡體   English   中英

檢索集合時出現MongoDB錯誤

[英]MongoDB error while retrieving collection

我在從Node.js應用程序中的數據庫獲取集合時遇到問題。 我正在使用Mongodb 3.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.');
    }
})

我可以在日志中看到Connected to 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本機驅動程序的API文檔中找不到任何名為getCollection函數 通常使用collection('mycoll')獲取collection('mycoll') 因此,您可以重寫此行:

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

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

請注意,如果使用v3.0或更高版本的驅動程序,則還必須修改連接功能。 對連接功能進行了一些更改(請參閱此處 )。 回調現在返回一個客戶端對象,而不是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();
    })
}

注意'database_name'字符串。 它應該是您的數據庫的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM