Shantanu Tomar
Shantanu Tomar

Reputation: 1712

Async/await while performing CRUD operations in mongoose

I am performing a delete operation using findByIdAndRemove mongoose query method and want to make sure that the deleted doc gets returned. I googled it and found that we pass a callback to findByIdAndRemove in which we pass err, doc args and if delete is successful the deleted value gets returned in doc which we can return from the fn call. But I am somewhat confused in async and await. I have deleteUserTask fn which internally calls async deleteUserTask fn which is promise based and expects a promise in return which when resolved (.then) I can get the value of the task which was deleted.

I am not sure how to return the value of doc from my async deleteUserTask fn which will be then resolved in .then promise and I can use it?

With below approach the value returned is null as I am not returning the doc value at all.

function deleteUserTask(req, res, next) {
  taskService
    .deleteUserTask(req.params.taskId)
    .then(task => {
      console.log(
        "Delete task request took " + (moment.now() - req.requestTime + " ms")
      );
      // below gives null
      console.log(task);
      res.json({ task });
    })
    .catch(err => next(err));
}

taskService.js

async function deleteUserTask(id) {
  return await Task.findByIdAndRemove(id, function(err, doc) {
    if (err) {
      return err;
    }
  });
}

Upvotes: 2

Views: 2307

Answers (1)

Estus Flask
Estus Flask

Reputation: 222354

A callback shouldn't be used with findByIdAndRemove in case promises are used. It should be:

async function deleteUserTask(id) {
  return await Task.findByIdAndRemove(id);
}

At this point there are no benefits from using async function, it could be simplified to:

function deleteUserTask(id) {
  return Task.findByIdAndRemove(id);
}

Upvotes: 3

Related Questions