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

190
Vistas
How to correctly cascade delete secondary object from MongoDB when account is deleted?

Users can create accounts on my app and are allowed to like, share X post.

The thing is that whenever a user deletes his/her account, everything related to them should also be deleted; so far I've been able to fix most of it but this:

await this.model('Post').updateMany(
    {
      'sharedby.user': this._id
    },
    {
      $pull: { 'sharedby.user': this._id }
    }
  );

Obviously, I'm using dot notation since user is one of the objects found in the sharedby object from the Post model. Here it is:

sharedby: [
      {
        user: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User'
        },
        post: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Post'
        }
      }
    ],

Whenever there's a share, this function gets triggered:

const newshare = await Post.findByIdAndUpdate(
    {
      _id: req.params.id,
      sharedby: { $ne: { user: req.user._id } }
    },
    {
      $push: { sharedby: { user: req.user._id, post: post._id } }
    },
    {
      new: true,
      runValidators: true,
      setDefaultsOnInsert: true
    }
  );

That's pretty much about it. I really have no idea why it's not working. Any suggestions? Thanks!.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Since you want to delete all the matching records from sharedby, I imagine you'll want to use $pullAll. Also, when using $pull or $pullAll, you should only use dot notation up to the Array boundary:

await this.model('Post').updateMany(
  {
    'sharedby.user': this._id
  },
  {
    $pullAll: { 'sharedby': { user: this._id } }
  }
);

See also: Remove Items from an Array of Documents

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