Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda