如何在Node.js中同步连接MongoDB

8

我希望利用Promise功能,可以同步连接到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,我无法通过谷歌或文档进行调试。

编辑:我曾假设promise是同步的,但事实并非如此。

3个回答

7
为了重用连接,我会创建一个像这样的模块。
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文件中创建了模块,您可以简单地使用require来获取数据库连接。

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

要建立连接,请使用以下方法:

var db = MongoConnection.getDb();

谢谢,我的问题有一个漏洞。我假设 Promise 是同步的,因此我的代码中有一些错误,但是感谢您提供这个非常有用的信息。 - Bazinga777

1

我一直在努力解决这个问题,特别是在AWS Lambda函数中设置和持久化MongoDb连接跨调用。

感谢@toszter的答案,我最终想出了以下解决方案:

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);
      }
    });
  });
}

在控制器或app.js中使用:

  const mongoConfig  =  require('mongoConfig');
  mongoConfig.getDB()
    .then(db => db.collection('collection').find({}))
    .catch(error => {...});


1

另一种使用ES6类的选项是创建一个单例对象,您可以反复访问。它受到@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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接