多个Node模块中的一个mongo连接

时间:2018-02-02 17:47:51

标签: node.js mongodb express connection-pooling

我试图让我的所有Node模块共享一个Mongo连接,并且我很难这样做。我已经看了一些关于这个的材料。下面是主文件,Mongo帮助程序文件和另一个尝试使用该连接的文件。问题是当路由文件尝试使用Mongo连接时,db为空。

Mongo帮助文件:

var mongo = require('mongodb').MongoClient

var _db

function connect(callback) {
    const host = '---'
    const database = '---'
    const user = '---'
    const pass = '---'
    const uri = 'mongodb://' + user + ':' + pass + '@' + host + '/' + database

    mongo.connect(uri, (err, client) => {
        console.log('Connected to Mongo')
        _db = client.db(database)
        return callback(err)
    })
}

function db() {
    return _db;
}

module.exports = {
    connect: connect,
    db: db
}

主档案:

var express = require('express')
var app = express()
var mongo = require('./helpers/mongo')
mongo.connect((err) => {
    if (err !== null) {
        console.log("Error connecting to Mongo: " + err)
        process.exit()
    }
})

var problems = require('./routes/problems.js')
app.use('/problem', problems)

app.listen(3000)

路线档案:

var express = require('express')
var router = express.Router()
var db = require('../helpers/mongo').db()

router.get('/stuff', (req, res) => {
    var problems = db.collection('problems')
    res.send('working correctly')
})

module.exports = router

1 个答案:

答案 0 :(得分:1)

猫鼬怎么样?

const mongoose = require('mongoose');

// connect to the database (mongodb)
mongoose.connect('mongodb:<host>/<db>', {useMongoClient: true});
mongoose.promise = global.Promise;
var db = mongoose.connection;

// Check for DB connection
db.once('open', function(){
  console.log('Connected to Mongo Db');
});

// Check for DB errors
db.on('error', function(err){
  console.log(err);
});