Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!