James
James

Reputation: 3815

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?

Upvotes: 2

Views: 576

Answers (2)

Cisco
Cisco

Reputation: 22952

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.

Upvotes: 3

ht_dreamer
ht_dreamer

Reputation: 13

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?

Upvotes: 0

Related Questions