猫鼬&关于生产的MongoDB连接

时间:2017-02-21 03:45:26

标签: node.js mongodb mongoose

在生产中使用猫鼬处理mongodb连接的最佳实践是什么? 这是我的代码

connectToDatabase.js

'use strict';
const mongoose = require('mongoose');
const mongodb = require('mongodb');
mongoose.Promise = require('bluebird');
const { Db, Server } = mongodb;

const database = 'test';

const connectToDatabase = (callback) => {
  if (process.env.NODE_ENV == 'test') return false;

  const db = new Db(database new Server('localhost', 27017));
  db.open()
    .then(() => {
      mongoose.connect(`mongodb://localhost/${database}`, { config: { autoIndex: false } });
        mongoose.connection
          .once('open', () => {
            console.log(`Connected to database ${database}`);
            callback(db);
          })
          .on('error', (error) => {
            console.warn('Warning', error);
          });
  });
};

module.exports = connectToDatabase;

app.js

const connectToDatabase = require('./connectToDatabase');

connectToDatabase(() => {
  // run server 
});

我不确切知道当数据库连接中断时发生了什么,mongoose是否再次尝试连接数据库?

0 个答案:

没有答案