Skimrande
Skimrande

Reputation: 831

Handling errors in Mongoose async/await call

I have an async function which looks up a Mongoose document by its ID and deletes it. My question is, is it ok to just have a catch clause to handle any error, or should I send in a callback as well (to catch any Mongoose errors?).

const myAsyncFunction = async (req, res) => {
    try {
      await myModel.findByIdAndDelete(req.params.docId)
      req.flash('info', 'Document was deleted.')
      res.redirect('/')
    } catch (error) {
      console.log(error)
    }
}

Or should I have

   await myModel.findByIdAndDelete(req.params.docId, function (error, user) {
        if (error) {
        // etc
        }    
    })

Upvotes: 1

Views: 380

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

Moongoose by default has callback style functions. In your case you need to add .exec() to be able to await it and catch exceptions. So something like this

const myAsyncFunction = async (req, res) => {
    try {
      await myModel.findByIdAndDelete(req.params.docId).exec();
      req.flash('info', 'Document was deleted.')
      res.redirect('/')
    } catch (error) {
      console.log(error)
    }
}

Upvotes: 1

Related Questions