简体   繁体   中英

MongoDB error while retrieving collection

I'm having a problem getting collection from the database in my Node.js application. I'm using 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. 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:

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:

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

I can't find any function named getCollection in the API documentation for the Node.js MongoDB native driver. Collections are usually fetched with 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. There were some changes done to the connection functions (see here ). The callback now returns a client object rather than the db object. 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. It should be the name of your database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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