简体   繁体   中英

NodeJS UnhandledPromise warning when connecting to MongoDB

I am trying to connect to my MongoDB instance using nodejs. I expose the endpoint /mongo which is supposed to trigger the connection and creation of a document in the mongo db, as follows:

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();
      });
}

When I hit the endpoint though, it returns with the following error:

(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)

I'm confused because the method invocation was wrapped around a try/catch block, even though the error log claims it wasn't. Where did I go wrong here?

There could be connection error in your environment. And the error was a rejected promise, you cannot catch it via the try / catch block because the error was generated on asynchronous call stack.

  1. an async function should alway return a promise:
async function invoke () {
  return new Promise((resolve, reject) => {
    client.connect(err => {
      if (err) return reject(err)
      ...
    })
  })
}
  1. the returned promise should be handled with.catch:
app.get('/mongo', (req, res) => {
  invoke().then(() => res.send('all good'))
    .catch(err => console.log('invoke error:', err))
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM