Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
Delete comment parents in mongoose

I am using typegoose and type-graphql. I have a CommentModel which has a parentId field that stores ObjectId of its parent comment.

What do I want?

I want to automate deletion of parents by using pre middleware. means when I delete a comment, I want it to delete all the comments that their parentId equals to targeted comment id.

An example:

So, when I delete comment 2, I expect the comment 1 will be deleted too.

comment: [
    {
        _id: 1,
        parentId: 2
    }, 
    {
        _id: 2,
        parentId: null
    }
]

but I can't.

What did I do?

this is my middleware:

@pre(/remove|delete/i, async function () {
    await CommentModel.deleteMany({ parentId: this._id })
})
export class Comment {
   ...
}

export const CommentModel = getModelForClass(Comment)

And this is how I delete

await CommentModel.findByIdAndDelete(ID_OF_COMMENT)

this operation will NEVER finish. and always show me the loading spinner. What do you suggest? Am I doing it wrong? or there is a better approach?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

every middelware have a next funxtion to continue change it like this:

@pre(/remove|delete/i, async function (next) {
await CommentModel.deleteMany({ parentId: this._id })
next();
})
about 4 years ago · Juan Pablo Isaza Relatório

0

This is how I fixed it:

@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 })))
        }
    }
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda