Im adding the mongo connection at server start to my global obj to access to it from any file
// app.js
mClient.connect(mongoUrl, function(err, db) {
global.mongo = db;
});
and using it like this
// store.js
global.mongo.collection(thisColl, function(err, collection) {
if (err) return self.emit("error", "collection not found");
collection.find(query, select).toArray(function(err, stores) {
if (err || !stores) return self.emit("error", "result not found");
return self.emit("done", stores);
});
});
but sometimes im getting and error that get fixed alone, I dont know how
// Error
{"code":"InternalError","message":"Cannot call method 'collection' of undefined"}
Im doing this becouse it doesnt open/close a connection on every request
I manage to make it work, maybe not the better way but works
// Create MongoDB connection
mClient.connect(mongoUrl, function(err, db) {
global.mongo = db;
// Start HTTP server
server.listen(4000, function() {
console.log("%s listening at %s", server.name, server.url);
});
});