如何在nodejs中同步连接到mongodb

我想利用承诺function,我可以同步连接到MongoDB,我可以通过传递到不同的模块重用连接。

这是我想出的东西

class MongoDB { constructor(db,collection) { this.collection = db.collection(collection); } find(query, projection) { if(projection) return this.collection.find(query, projection); else return this.collection.find(query); } } class Crew extends MongoDB { constructor(db) { super(db,'crews'); } validate() { } } 

我想在我的初始代码中设置一个连接,就像下面的代码一样,然后重复使用不同类的连接,就像mongoose或monk一样,只使用node-mongodb-native包。

 MongoClient.connect(url) .then( (err,dbase) => { global.DB = dbase; }); var Crew = new CrewModel(global.DB); Crew.find({}) .then(function(resp) { console.log(resp); }); 

现在,db在主MongoDB类中返回undefined,不能通过google或文档debugging这个。

编辑:我曾以为承诺是同步的,但事实并非如此。

要重新使用连接,我会创build一个像这样的模块。

 module.exports = { connect: function(dbName, callback ) { MongoClient.connect(dbName, function(err, db) { _db = db; return callback( err ); }); }, getDb: function() { return _db; } }; 

之后,您可以在开始您的应用程序之前连接到数据库

 MongoConnection.connect("mongodb://localhost:27017/myDatabase", function(err){ app.listen(3000, function () { // you code }); }); 

考虑到您在js文件中创build了模块,您可以简单地使用require来获取数据库连接

 var dbConnection = require("./myMongoConnection.js"); 

并获得连接使用

 var db = MongoConnection.getDb(); 

另一个使用ES6类的选项创build一个可以重复访问的单例对象。 它的灵感来自@ user3134009的答案在这里 。

 const EventEmitter = require('events'); const MongoClient = require('mongodb').MongoClient; const config = require('config'); let _db = null; class MongoDBConnection extends EventEmitter { constructor() { super(); this.emit("dbinit", this); if (_db == null) { console.log("Connecting to MongoDB..."); MongoClient.connect(config.dbs.mongo.url, config.dbs.mongo.options, (err, db) => { if (err) { console.error("MongoDB Connection Error", err); _db = null; } else { console.log("Connected to MongoDB", config.dbs.mongo.url); db.on('close', () => { console.log("MongoDB closed", arguments); _db = null; }); db.on('reconnect', () => { console.log("MongoDB reconnected", arguments); _db = db; }); db.on('timeout', () => { console.log("MongoDB timeout", arguments); }); _db = db; this.emit('dbconnect', _db); } }); } } getDB() { return _db; } } module.exports = new MongoDBConnection(); 

我一直在努力解决这个问题,特别是在跨调用的AWS lambda函数中build立和保持MongoDb连接。 感谢@toszter答案,我终于想出了以下解决scheme:

 const mongodb = require('mongodb'); const config = require('./config.json')[env]; const client = mongodb.MongoClient; const mongodbUri = `mongodb://${config.mongo.user}:${config.mongo.password}@${config.mongo.url}/${config.mongo.database}`; const options = { poolSize: 100, connectTimeoutMS: 120000, socketTimeoutMS: 1440000 }; // connection object let _db = null; class MongoDBConnection { constructor() {} // return a promise to the existing connection or the connection function getDB() { return (_db ? Promise.resolve(_db) : mConnect()); } } module.exports = new MongoDBConnection(); // transforms into a promise Mongo's client.connect function mConnect() { return new Promise((resolve, reject) => { console.log('Connecting to Mongo...'); client.connect(mongodbUri, options, (error, db) => { if (error) { _db = null; return reject(error); } else { console.log('Connected to Mongo...'); _db = db; resolve(db); } }); }); }