我正在关注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);
})
}
}
然后我在db.connect()
文件中调用app.js
,如下所示:
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(); });
});
在req.on('end'.....
的{{1}}中触发警告的exports.close
行。
我假设db.js
作为回调传入,因此我不确定为什么它会返回错误消息。
此外,我假设我的代码中的行返回错误消息很有用,因此它会关闭未使用的数据库连接。这首先是这种方法吗?
谢谢。
答案 0 :(得分:1)
您的exports.close = (done) => {...}
函数需要将完成的回调传递给它。
但是,你没有在这一行中传递回调:
req.on('end', () => { db.close(); });
您可以修改close函数,以便回调是可选的:
exports.close = (done) => {
done = done || function() {}; // make sure there's always a callback here
if (state.db) {
state.db.close((err, result) => {
state.db = null;
state.mode = null;
done(err);
})
}
}
我假设已完成作为回调传入,所以我不确定为什么它会返回错误消息。
您正在其他地方(例如.connect()
)传递回调,但db.close()
没有传递回传。
另外,我假设我的代码中的行返回错误消息是有用的,因此它会关闭未使用的数据库连接。这首先是这种方法吗?
是的,将err
值传递给完成回调是传递异步错误值的典型方法。