首页 > 解决方案 > 连接到 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 块周围,即使错误日志声称它不是。我在这里哪里做错了?

标签: javascriptnode.jsmongodb

解决方案


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

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

推荐阅读