Home > OS >  Deleting neseted document - mongoose
Deleting neseted document - mongoose

Time:10-31

I am trying to delete user model with all the nested documents inside him. There is a Post model inside the user and Comment model inside the post. Is there an easy way to delete all of the nested documents? I tried this way but this is look long and messy.

const user = await User.findById(userId).populate({
    path: "posts",
    select: ["comments"],
  });

const userDeletingSession = await mongoose.startSession();
userDeletingSession.startTransaction();

for await (const post of userPosts) {
  await Comment.deleteMany(
    { _id: post.comments },
    { session: userDeletingSession }
  );
}
await Post.deleteMany({ _id: userPosts }, { session: userDeletingSession });
await user.remove({ session: userDeletingSession });

await userDeletingSession.commitTransaction();

CodePudding user response:

There is unfortunately not much you can do to simplify your code. The reason is that MongoDB is not a database which enforces structured data (like SQL databases). It's up to the user to enforce this manually, which is always a little bit messy.

Nevertheless here are some hints:

  1. Check if a NoSQL database is really the best choice for your use cases.
  2. Try to use hooks for generalizing this behavior. That way you won't have to rewrite the logic in different places and your structure gets enforced at least on schema definition level, not on business logic level.
  3. Use $in operator instead of iterating over the posts.
const user = await User.findById(userId).populate({
    path: "posts",
    select: ["comments"],
  });

const userDeletingSession = await mongoose.startSession();
userDeletingSession.startTransaction();

await Comment.deleteMany(
  { _id: { $in: userPosts.map(post => post.comments) } },
  { session: userDeletingSession }
);

await Post.deleteMany({ _id: userPosts }, { session: userDeletingSession });
await user.remove({ session: userDeletingSession });

await userDeletingSession.commitTransaction();
  • Related