简体   繁体   English

检索集合时出现MongoDB错误

[英]MongoDB error while retrieving collection

I'm having a problem getting collection from the database in my Node.js application. 我在从Node.js应用程序中的数据库获取集合时遇到问题。 I'm using Mongodb 3.6. 我正在使用Mongodb 3.6。

That's how I set it up: 我就是这样设置的:

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);
    });
}

In the main file I do: 在主文件中,我这样做:

'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.');
    }
})

I can see in the log the Connected to db. 我可以在日志中看到Connected to db. prompt, so the connection works fine. 提示,因此连接正常。 After that I try to call some function to add/retrieve data from the db and i get the error: 之后,我尝试调用一些函数从数据库中添加/检索数据,并且出现错误:

TypeError: get(...).getCollection is not a function
    at Object.exports.return_collection

If I try to print the state.db variable I get the following result: 如果我尝试打印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] } } }

What am I missing? 我想念什么? In the mongo console everything looks fine: 在mongo控制台中,一切看起来都很好:

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

I can't find any function named getCollection in the API documentation for the Node.js MongoDB native driver. 在Node.js MongoDB本机驱动程序的API文档中找不到任何名为getCollection函数 Collections are usually fetched with collection('mycoll') . 通常使用collection('mycoll')获取collection('mycoll') So you can rewrite this line: 因此,您可以重写此行:

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

to

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

Note that if you use v3.0 or later of the driver you have to modify the connect function as well. 请注意,如果使用v3.0或更高版本的驱动程序,则还必须修改连接功能。 There were some changes done to the connection functions (see here ). 对连接功能进行了一些更改(请参阅此处 )。 The callback now returns a client object rather than the db object. 回调现在返回一个客户端对象,而不是db对象。 So you'll have to change your function to: 因此,您必须将功能更改为:

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();
    })
}

Note the 'database_name' string. 注意'database_name'字符串。 It should be the name of your database. 它应该是您的数据库的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM