Search code examples
node.jsmongodbmongoose

How to remove a Mongoose document if I have an instance of it already?


I am not sure if I am doing this naively or not, but I suspect that there's a more efficient and clever way of handling this situation.

Let's say I have an instance of a document that I then need to remove from MongoDB following some logic checks:

    const post = await Post.findById(req.params.postId);
    // Check whether the logged user owns this post
    if (post._userId.equals(req.user._id)) {
      await Post.findByIdAndRemove(req.params.postId);

Is there a way to avoid retrieving the same document twice?


Solution

  • All models have a remove so simply call await post.remove().

    https://mongoosejs.com/docs/4.x/docs/api.html#model_Model-remove


    Edit 2024-03-07: Updated link to reflect documentation at the time of question.