javascript - 连接到 MongoDB 时出现 NodeJS UnhandledPromise 警告
问题描述
我正在尝试使用 nodejs 连接到我的 MongoDB 实例。我公开了/mongo
应该触发连接并在 mongo db 中创建文档的端点,如下所示:
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 块捕获它,因为错误是在异步调用堆栈上生成的。
- 一个异步函数应该总是返回一个承诺:
async function invoke () {
return new Promise((resolve, reject) => {
client.connect(err => {
if (err) return reject(err)
...
})
})
}
- 返回的承诺应使用 .catch 处理:
app.get('/mongo', (req, res) => {
invoke().then(() => res.send('all good'))
.catch(err => console.log('invoke error:', err))
})
推荐阅读
- python - 训练 SSD 给出 ValueError: Can't load save_path when it is None
- python - Pandas 按两列分组并在第三列中计算共享值
- json - 错误:尝试构建导航时 Dart 中未定义的名称“小部件”
- java - 减少java中的自定义对象列表
- python - aiohttp 抛出 nasdaq.com 的服务器断开连接
- json - 如何将对象转换为 Jooq JSON
- python - 使用draw_artist时如何使matplotlib自动缩放y轴?
- python - 在 Python 中将数据集的数字范围更改为文本
- regex - 正则表达式解析姓氏和名字的字符串,其中姓氏可能是大写和/或连接的
- javascript - 如何等待来自 API 的数据作为组件中的道具?