尝试连接到mongodb时节点应用程序错误

时间:2016-06-25 08:33:22

标签: javascript node.js mongodb

enter image description here我正在尝试学习节点并使用一些教程构建应用程序,同时使用mongoDB作为数据库。我有这两个javascript文件,database.js用于连接到index.js中的mongo db和seedDatabase()函数来播种我拥有的数据。

database.js:

(function (database) {

var mongodb = require("mongodb");
var mongoUrl = "mongodb://localhost:27017/theBoard";
var theDb = null;

database.getDb = function (next) {
    if (!theDb) {
        // connect to the database
        mongodb.MongoClient.connect(mongoUrl, function (err, db) {
            if (err) {
                next(err, null);
            } else {
                theDb = {
                    db: db,
                    notes: db.collection("notes")
                };
            }
        });
    } else {
        next(null, theDb);
    }
}

});

index.js:

    (function (data)
{
    var seedData = require("./seedData");
    var database = require("./database.js");

    data.getNoteCaregories = function (next)
    {
        next(null, seedData.initialNotes);
    };

    function seedDatabase() {
        database.getDb(function (err, db) {
            if (err) {
                console.log("Failed to seed database: " + err);
            } else {
                // test to see if data exists yet
                db.notes.count(function (err, db) {
                    if (err) {
                        console.log("Failed to retrieve database count.");
                    } else {
                        if (count == 0) {
                            console.log("Seeding the Database...");
                            seedData.initialNotes.forEach(function (item) {
                                db.notes.insert(item, function (err) {
                                    if (err)
                                        console.log("Failed to insert note into database");
                                });
                            });
                        } else {
                            console.log("Database already seeded");
                        }
                    }
                });
            }
        });
    }

    seedDatabase();

})(module.exports);

1 个答案:

答案 0 :(得分:0)

这是因为你永远不会在database.js文件中导出函数getDb或对象database

更新你的database.js:

exports.getDb = function (next) {
    if (!theDb) {
        // connect to the database
        mongodb.MongoClient.connect(mongoUrl, function (err, db) {
            if (err) {
                next(err, null);
            } else {
                theDb = {
                    db: db,
                    notes: db.collection("notes")
                };
            }
        });
    } else {
        next(null, theDb);
    }
}