0

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?

James
  • 3,597
  • 11
  • 41
  • 76

2 Answers2

2

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

http://mongoosejs.com/docs/api.html#model_Model-remove

Cisco
  • 20,972
  • 5
  • 38
  • 60
0

Reference to one of the solution of the below post . remove is now deprecated. Use deleteOne() deleteMany() fineOneAndDelete() instead. How do I remove documents using Node.js Mongoose?

ht_dreamer
  • 13
  • 4