如何在NodeJS应用程序和模块之间正确重用到MongoDB的连接
server.js
var MongoClient = require('mongodb').MongoClient; var mongo = {}; // this is passed to modules and code MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) { if (!err) { console.log("We are connected"); // these tables will be passed to modules as part of mongo object mongo.dbUsers = db.collection("users"); mongo.dbDisciplines = db.collection("disciplines"); console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules } else console.log(err); }); var users = new(require("./models/user"))(app, mongo); console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined
models/user
Users = function(app, mongo) {Users.prototype.addUser = function() { console.log("add user");}Users.prototype.getAll = function() { return "all users " + mongo.dbUsers; }}module.exports = Users;
一只斗牛犬
ABOUTYOU
慕容708150
相关分类