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

86
Visualizações
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 Respostas
Responde à pergunta

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 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