Since access and initialization of the MongoDB database is asynchronous in Node.js, I would like to define one module for each collection that exports wrapped db calls after db initialization.
Such a module "Cars.model.js" is as follows:
var db = require("mongodb"); db.collection("cars", function(err, col) { exports.getCars = function(callback) { col.find({}, callback); }; });
so that other modules can start:
var carModel = require("Cars.model.js").getCars; getCars(err, cars) {
It happened to me that getCars was undefined, because db access was not yet initialized at the time of launching my second module.
How do you deal with creating such asynchronous db models?
Adrien joly
source share