AutumnSky
AutumnSky

Reputation: 414

Is there anyway to remove one Document and then update ref model's ObjectId array automatically?

Here my models.

const UserSchema = mongoose.Schema({
  name: String,
  comments: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Comment'
    }
  ]
});

const CommentSchema = new mongoose.Schema({
  comment: String,
  creatorId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
});

User could have many comments.
So User and Comment is one-to-many relationship.
When User create a new comment, A new Comment is created and it's ObjectId is pushed to User's comments array.

What I want to do is, delete Comment's ObjectId automatically when delete one Comment.

I know I can do this with two queries.
Is there anyway to combine these two to one?

await user.comments.remove(comment.id);
await comment.remove();

Upvotes: 1

Views: 25

Answers (1)

mickl
mickl

Reputation: 49945

You can't run remove on two collections / schemas however you can take advantage of Post Middleware and define such middleware on CommentsSchema:

CommentsSchema.post('remove', function(comment) {
    await UserSchema.update({ _id: comment.creatorId }, { $pull: { comments: comment._id } })
});

Upvotes: 2

Related Questions