0

enter image description hereI am trying to learn node and build an app using a few tutorials, also using mongoDB as database. I have these two javascript files, database.js for connecting to mongo db and seedDatabase() function in index.js to seed the data that I have.

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);
inthevortex
  • 334
  • 5
  • 20

1 Answers1

0

It's because you never export the function getDbor the object database in your database.js file.

Update your database.js for something like that :

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);
    }
}
NotBad4U
  • 1,502
  • 1
  • 16
  • 23