TypeError:无法读取属性'集合'未定义的

时间:2016-01-12 06:54:06

标签: node.js mongodb node-mongodb-native

我是nodejs的新手,目前正在研究node.js和mongodb。这是我的mongodb连接代码

var mongodb = require("mongodb");

var MongoClient = mongodb.MongoClient;

var url = 'mongodb://localhost:27017/mydb';

var mongodbStore = {};

var db;

MongoClient.connect(url, function (err, dataBase) {
    if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
    } else {

        debug("Connected to mongodb. Initialising saved listeners...");
        db = dataBase;
        var manager = require('./managers/manager');
    }
});

mongodbStore.add = function(name, data) {
    var collection = db.collection('listeners');

    if (collection) {
        collection.insert("listener", JSON.stringify(data));
    }
};

我会打电话给#34;添加"从我的另一个文件中运行。但是现在我在添加功能的第一行收到错误

var collection = db.collection('listeners');

错误是:

TypeError: Cannot read property 'collection' of undefined
    at Object.mongodbStore.add (C:\Node.js Listeners 2\mongodbStore.js:54:21)
    at C:\Node.js Listeners 2\managers\manager.js:46:18
    at Server.<anonymous> (C:\Node.js Listeners 2\managers\tcpManager.js:54:10)
    at Server.emit (events.js:104:17)
    at net.js:1171:12
    at process._tickCallback (node.js:355:11)

任何人都可以告诉我,这里有什么问题以及什么是正确的方法?

1 个答案:

答案 0 :(得分:0)

这是因为db是不确定的,因为您是从回调中分配其值的。您需要像这样将代码移到传递给connect的回调中。

var mongodb = require("mongodb");

var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/mydb';
var mongodbStore = {};

MongoClient.connect(url, function (err, db) {
    if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
    } else {

        debug("Connected to mongodb. Initialising saved listeners...");
        var manager = require('./managers/manager');

        mongodbStore.add = function(name, data) {
           var collection = db.collection('listeners');

           if (collection) {
              collection.insert("listener", JSON.stringify(data));
           }
        };
    }
});