在开发 Web 应用程序时,我想要一个可以在不同模块中重用的 MongoDB 单例连接。我通过使用 Promise 来做到这一点。到目前为止我尝试了以下方法:
Server.js
module.exports = new Promise ((res, rej) => {
let MongoDB;
MongoClient.connect('mongodb://localhost:27017/WIGAMEX',{poolSize: 30}, function(err, db) {
// console.log(db);
MongoDB = db;
});
if(MongoDB) {
res(db);
}
rej('no DB');
});
模块 1
const server = require('../server.js');
server.then( (db) => {console.log(db) });
它现在说:
TypeError: server.then is not a function
问题:
我做错了什么以及如何让它发挥作用?
最佳答案
你做错了两件事
首先,您应该将返回值包含在连接回调中。
module.exports = new Promise ((res, rej) => {
MongoClient.connect('mongodb://localhost:27017/WIGAMEX',{
poolSize: 30,
}, function(err, db) {
if (err) {
return rej(err);
}
return res(db);
});
});
第二个你返回的是一个 Promise 函数,你必须在解决它之前调用它
const server = require('../server.js');
server()
.then((db) => {
console.log(db)
})
.catch((err) => {
// treat error
});
关于javascript - MongoDB 将 mongo 实例包装在 Promise 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50240021/