簡體   English   中英

Mongoose 刪除很多子文檔和相關子文檔

[英]Mongoose deleteMany subdocuments and related subdocuments

我有一個包含一系列子文檔的文檔項目,以及一個架構任務。 任務有一組帶有模式注釋的子文檔。

const projectSchema = new Schema({
  _id: Schema.Types.ObjectId,
  name: { type: String, required: true, unique: true },
  description: { type: String, default: '' },
  tasks: [{ type: Schema.Types.ObjectId, ref: 'Threads' }]
});
module.exports = mongoose.model('Project', projectSchema);

const tasksSchema = new Schema({
  projectId: { type: Schema.Types.ObjectId },
  _id: Schema.Types.ObjectId,
  title: { type: String, required: true },
  text: { type: String, required: true },
  comments: [{ type: Schema.Types.ObjectId, ref: 'Replies' }]
})
module.exports = mongoose.model('Tasks', tasksSchema);

const commentSchema = new Schema({
  taskId: { type: Schema.Types.ObjectId },
  _id: Schema.Types.ObjectId,
  text: { type: String, required: true }
})
module.exports = mongoose.model('Comment', commentSchema);

當我刪除項目文檔時,我想刪除與該項目相關的每個任務和每個評論。 要刪除項目,我使用 findOneAndDelete 所以我設置了一個發布中間件來刪除所有任務

projectSchema.post('findOneAndDelete', function(doc, next) {
  mongoose.model('Tasks').deleteMany({ projectId: doc._id }).exec(); 
  next();
})

但是現在我不知道如何刪除每個評論,因為deletemany返回一個帶有操作結果的對象。 我應該映射任務數組並每次調用 findOneAndDelete 然后刪除每條評論嗎? 對於很多任務來說,它看起來效率很低。

如何在帖子中嵌入評論? 因為它是一對多(不是很大)的關系。 因此,在刪除項目的代碼中,首先刪除包含所有評論的所有帖子,只有在成功刪除項目后。 它還將顯着提高您的閱讀性能,因為您只需要返回單個帖子文檔而不是多個(1 個帖子 + 多個評論)文檔。

也可以將帖子嵌入到項目中,但根據可能帖子的大小和數量,最好將其作為單獨的文檔保存。 在這種情況下,您需要一些邏輯來確保一致性。 在這里你可以使用 mongodb 的新功能,事務。 但是我認為在這種情況下不需要事務。(我也覺得現在它很不穩定)您可以使用“最終一致性”方法。

基本上,您只需刪除與項目相關的所有帖子,然后刪除一個項目。 然后你運行批處理來檢查是否有任何不一致。(檢查是否有任何帖子不存在其項目。如果不存在則刪除帖子)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM