节点服务器启动时的MongoDB连接

时间:2017-06-27 17:44:35

标签: node.js mongodb mongoose

我使用mongoose与MongoDB服务器建立连接,我在单独的文件中声明了以下代码

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/fs');

var db = mongoose.connection;
db.on('error', function dbError(){
    console.log('Connection Error');
});

db.once('connected', function dbConnected(){
    console.log('Connected to the database');
});

db.on('disconnected', function dbDisconnected(){
    console.log('Database disconnected');
});

process.on('SIGINT', function closeConnection(){
    mongoose.connection.close(function(){
        console.log('Server is down, closing the connection');
        process.exit(0);
    });
});

我的主服务器代码如下

var express = require('express'),
    port = process.env.PORT || 8443;

var app = express();
//other middlewares
.......

app.listen(port, function () {
    /* eslint-disable no-console */
    console.log('Sample service running on %s:%d', this.address().address, this.address().port);
    /* eslint-disable no-console */
});

我不确定如何导入在mongoose文件中建立的连接并在我的主服务器中使用它。因此,无论何时服务器启动,我都希望它首先连接到MongoDB服务器。

2 个答案:

答案 0 :(得分:0)

只需导入服务器文件顶部的mongoose连接文件:

require('path/to/file');

...然后你的猫鼬模型将自动使用该连接。

答案 1 :(得分:0)

导出内容。

var exports = module.exports = {};

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/fs');
var db = mongoose.connection;

exports.connect = function(){

  db.on('error', function dbError(){
      console.log('Connection Error');
  });
  db.once('connected', function dbConnected(){
    console.log('Connected to the database');
  });

  db.on('disconnected', function dbDisconnected(){
    console.log('Database disconnected');
  });

  process.on('SIGINT', function closeConnection(){
    mongoose.connection.close(function(){
        console.log('Server is down, closing the connection');
        process.exit(0);
    });
  });
}

导入您的文件,然后调用该函数。

var foo = require("/path/to/file");

foo.connect();