我正在嘗試洗掉包含所有嵌套檔案的用戶模型。用戶內部有一個帖子模型,帖子內部有一個評論模型。有沒有一種簡單的方法可以洗掉所有嵌套檔案?我試過這種方式,但這看起來又長又亂。
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();
uj5u.com熱心網友回復:
不幸的是,您無能為力來簡化您的代碼。原因是 MongoDB 不是一個強制執行結構化資料的資料庫(如 SQL 資料庫)。由用戶手動執行此操作,這總是有點混亂。
不過這里有一些提示:
- 檢查 NoSQL 資料庫是否真的是您的用例的最佳選擇。
- 嘗試使用鉤子來概括這種行為。這樣您就不必在不同的地方重寫邏輯,并且您的結構至少在模式定義級別而不是業務邏輯級別上得到強制執行。
- 使用
$in運算子而不是遍歷帖子。
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524245.html
上一篇:如何在Postman回應中傳遞Mongoose驗證錯誤
下一篇:在地圖中使用updateOne,將過濾器設定為唯一的id,$set是檔案,而upsert是true。即使這樣,也會創建新檔案
