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

85
Vistas
Keep only 5 elements in array removing the last one when pushing mongodb to always have only 5 elements

I need to maintain an array of objects in MondoDB with only 5 elements, if another element is to be added, the first one is deleted and the new one is added, but always only 5 elements. Is there any way to do this?

I'm using Express and MongoDB, this is part of my model where I need to keep the array with only 5 objects:

    lastModificationBy: [{
        uid:{
            type: String,
            required:true
        },
        username:{
            type: String,
            required:true
        },
        date:{
            type: Number,
            required:true
        }
    }],

To push each element in the array I use the following:

            let product = await Product.findByIdAndUpdate( id, 
                {
                    $set: data,
                    $push: { 'lastModificationBy': lastModification }
                }
            ); 

Thanks!

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

0

You are using Mongoose and not Mongodb native driver.

Please try and let me know if below works. I dont have access to MongoDB so could not test

let product = await Product.findByIdAndUpdate(id, {
  $set: data,
  $push: {
    'lastModificationBy': {
      $each: [lastModification],
      $slice: -5 
    }
  }
);
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