As MongoDB database access and initialization is asynchronous on Node.js, I would like to define one module per collection that exports wrapped db calls after db initialization.
Such a "Cars.model.js" module looks like that:
var db = require("mongodb");
db.collection("cars", function(err, col) {
exports.getCars = function(callback) {
col.find({}, callback);
};
});
so that other modules can run:
var carModel = require("Cars.model.js").getCars;
getCars(err, cars) {
// (do something with cars here...)
};
It happened to me that getCars
was undefined, because db access was not yet initialized at the time my second module was run.
How do you deal with creating such asynchronous db models?