NodeJS mongo .find不是一个函数

时间:2016-07-28 15:30:06

标签: javascript node.js mongodb find typeerror

我正在使用node.js实现一个小型服务器应用程序,并遇到了一个无法识别collection.find()方法的问题。

这是我的代码:

// THIS FUNCTION WORKS CORRECTLY
var find_all_seasons = function (callback) {
    var season_collection = db.get().collection('season_collection');
    // Find some documents
    season_collection.find({}).toArray(function(err, docs) {
        assert.equal(err, null);
        console.log("Found the following records");
        console.log(docs)
        callback(docs);
    });
};

// HERE I ALWAYS GET THE EXCEPTION
var find_speaker_by_name = function (name, callback) {
    var speaker_collection = db.get().collection('speaker_collection').find({"name":name})(function(err, doc) {
        assert.equal(err, null);
        console.log("Found the following records");
        console.log(doc.name)
        callback(doc);
    });
};

........
app.get('/api/speakers/:name', function (req, res) {
    var name = req.params.name;

    find_speaker_by_name(name, function (err, result) {
        if (err)
            res.send(err);

        res.json(result);
    })
});

例外:

TypeError: db.get(...).collection(...).find(...) is not a function
    at find_speaker_by_name 

我的数据库连接:

var MongoClient = require('mongodb').MongoClient

var state = {
    db: null
};

exports.connect = function(url, done) {
    if (state.db) return done();

    MongoClient.connect(url, function(err, db) {
        if (err) return done(err);
        state.db = db;
        done()
    })
};

exports.get = function() {
    return state.db
};

exports.close = function(done) {
    if (state.db) {
        state.db.close(function(err, result) {
            state.db = null
            state.mode = null
            done(err)
        })
    }
};

0 个答案:

没有答案