我正在使用 typegoose 和 type-graphql。我有一個欄位,CommentModel該parentId欄位存盤其父注釋的 ObjectId。
我想要什么?
我想通過使用pre中間件自動洗掉父母。意味著當我洗掉評論時,我希望它洗掉所有parentId等于目標評論 ID 的評論。
一個例子:
因此,當我洗掉評論 2 時,我希望評論 1 也會被洗掉。
comment: [
{
_id: 1,
parentId: 2
},
{
_id: 2,
parentId: null
}
]
但我不能。
我做了什么?
這是我的中間件:
@pre(/remove|delete/i, async function () {
await CommentModel.deleteMany({ parentId: this._id })
})
export class Comment {
...
}
export const CommentModel = getModelForClass(Comment)
這就是我洗掉的方式
await CommentModel.findByIdAndDelete(ID_OF_COMMENT)
此操作永遠不會完成。并始終向我展示加載微調器。你有什么建議?我做錯了嗎?或者有更好的方法?
uj5u.com熱心網友回復:
每個中間件都有一個下一個功能來繼續像這樣改變它:
@pre(/remove|delete/i, async function (next) {
await CommentModel.deleteMany({ parentId: this._id })
next();
})
uj5u.com熱心網友回復:
這是我修復它的方式:
@post(/remove|delete/i, async function (comment: DocumentType<Comment> | null) {
if (comment?._id) {
const children = await CommentModel.find({ parentId: comment._id }).lean().exec()
await CommentModel.deleteMany({ parentId: comment._id })
if (children) {
await Promise.all(children.map(child => child?._id && CommentModel.deleteMany({ parentId: child._id })))
}
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/375265.html
標籤:javascript 节点.js MongoDB 猫鼬 猫鼬模式
