如何在NodeJS应用程序和模块之间正确重用到MongoDB的连接我一直在阅读,但仍然困惑于如何在整个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;现在我有可怕的感觉,这是错误的,所以这种方法是否有明显的问题,如果是的话,如何使它更好?
3 回答
一只斗牛犬
TA贡献1784条经验 获得超2个赞
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
TA贡献1812条经验 获得超5个赞
mongoUtil.js
const MongoClient = require( 'mongodb' ).MongoClient;const url = "mongodb://localhost:27017";var _db;module.exports = { connectToServer: function( callback ) { MongoClient.connect( url, { useNewUrlParser: true }, function( err, client ) { _db = client.db('test_db'); return callback( err ); } ); }, getDb: function() { return _db; }};
app.js
:
var mongoUtil = require( 'mongoUtil' );mongoUtil.connectToServer( function( err, client ) { if (err) console.log(err); // start the rest of your app here} );
.js
var mongoUtil = require( 'mongoUtil' );var db = mongoUtil.getDb();db.collection( 'users' ).find();
require
_db
mongoUtil.getDb()
慕容708150
TA贡献1831条经验 获得超4个赞
./db/monGodb.js
const MongoClient = require('mongodb').MongoClient const uri = 'mongodb://user:password@localhost:27017/dbName' let _db const connectDB = async (callback) => { try { MongoClient.connect(uri, (err, db) => { _db = db return callback(err) }) } catch (e) { throw e } } const getDB = () => _db const disconnectDB = () => _db.close() module.exports = { connectDB, getDB, disconnectDB }
./index.js
// Load MongoDB utils const MongoDB = require('./db/mongodb') // Load queries & mutations const Users = require('./users') // Improve debugging process.on('unhandledRejection', (reason, p) => { console.log('Unhandled Rejection at:', p, 'reason:', reason) }) const seedUser = { name: 'Bob Alice', email: 'test@dev.null', bonusSetting: true } // Connect to MongoDB and put server instantiation code inside // because we start the connection first MongoDB.connectDB(async (err) => { if (err) throw err // Load db & collections const db = MongoDB.getDB() const users = db.collection('users') try { // Run some sample operations // and pass users collection into models const newUser = await Users.createUser(users, seedUser) const listUsers = await Users.getUsers(users) const findUser = await Users.findUserById(users, newUser._id) console.log('CREATE USER') console.log(newUser) console.log('GET ALL USERS') console.log(listUsers) console.log('FIND USER') console.log(findUser) } catch (e) { throw e } const desired = true if (desired) { // Use disconnectDB for clean driver disconnect MongoDB.disconnectDB() process.exit(0) } // Server code anywhere above here inside connectDB() })
./user/index.js
const ObjectID = require('mongodb').ObjectID // Notice how the users collection is passed into the models const createUser = async (users, user) => { try { const results = await users.insertOne(user) return results.ops[0] } catch (e) { throw e } } const getUsers = async (users) => { try { const results = await users.find().toArray() return results } catch (e) { throw e } } const findUserById = async (users, id) => { try { if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.' const results = await users.findOne(ObjectID(id)) return results } catch (e) { throw e } } // Export garbage as methods on the Users object module.exports = { createUser, getUsers, findUserById }
添加回答
举报
0/150
提交
取消