Home > Software engineering >  Keep only 5 elements in array removing the last one when pushing mongodb to always have only 5 eleme
Keep only 5 elements in array removing the last one when pushing mongodb to always have only 5 eleme

Time:01-21

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!

CodePudding user response:

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 
    }
  }
);
  •  Tags:  
  • Related