【发布时间】:2017-11-22 09:54:13
【问题描述】:
我正在关注terlici.com 上关于将 MongoDB 连接到 Web 应用程序的其余部分的教程。
我配置了一个db.js 文件,其内容如下:
DB.JS:
const MongoClient = require('mongodb').MongoClient;
const state = {
db: null
}
exports.connect = (url, done) => {
if (state.db) return done();
MongoClient.connect(url, (err, db) => {
if (err) return done(err);
state.db = db;
done();
});
}
exports.get = () => {
return state.db;
}
exports.close = (done) => {
if (state.db) {
state.db.close((err, result) => {
state.db = null;
state.mode = null;
done(err);
})
}
}
然后我在我的app.js 文件中调用db.connect(),如下所示:
APP.JS:
app.use((req, res, next) => {
db.connect('mongodb-url-goes-here', (e) => {
if (e) return next(e);
next();
});
// cleanup
req.on('end', () => { db.close(); });
});
在db.js 中触发exports.close 警告的req.on('end'..... 行。
我假设 done 作为回调传入,所以我不确定它为什么返回错误消息。
另外,我假设我的代码中返回错误消息的行很有用,因此它会关闭未使用的数据库连接。首先这样做是否合适?
谢谢。
【问题讨论】: