NodeJS连接MongoDB时UnhandledPromise警告



我正在尝试使用nodejs连接到我的MongoDB实例。我公开端点/mongo,它应该在mongodb中触发文档的连接和创建,如下所示:

app.get('/mongo', (req, res) => {
try{
invoke();
} catch(err){
console.log(err);
}
res.send('all good.');
});

async function invoke() {
client.connect(err => {
const collection = client.db("CodigoInitiative").collection("Registered");

//create document to be inserted
const pizzaDocument = {
name: "Pizza",
shape: "round",
toppings: [ "Pepperoni", "mozzarella" ],
};

// perform actions on the collection object
const result = collection.insertOne(pizzaDocument);
console.log(result.insertedCount);

//close the database connection
client.close();
});
}

当我到达端点时,它返回以下错误:

(node:15052) UnhandledPromiseRejectionWarning: MongoError: topology was destroyed. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

我很困惑,因为方法调用被包裹在一个try/catch块,即使错误日志声称它不是。我哪里出错了?

您的环境中可能存在连接错误。如果错误是一个被拒绝的承诺,你不能通过try/catch块捕获它,因为错误是在异步调用堆栈上生成的。

  1. async函数应该总是返回承诺:
async function invoke () {
return new Promise((resolve, reject) => {
client.connect(err => {
if (err) return reject(err)
...
})
})
}
  1. 返回的promise应该用。catch:
  2. 处理
app.get('/mongo', (req, res) => {
invoke().then(() => res.send('all good'))
.catch(err => console.log('invoke error:', err))
})

最新更新