I have a unique requirement where I need to maintain an array of objects in MongoDB with a maximum of 5 elements. Whenever a new element is added, the oldest one should be removed to ensure that there are always only 5 elements in the array. Is there a way to achieve this?
Currently, I am working with Express and MongoDB, and this is a snippet from my model where I need to manage the array with just 5 objects:
lastModificationBy: [{
uid:{
type: String,
required:true
},
username:{
type: String,
required:true
},
date:{
type: Number,
required:true
}
}],
To add each new element to the array, I use the following method:
let product = await Product.findByIdAndUpdate( id,
{
$set: data,
$push: { 'lastModificationBy': lastModification }
}
);
Any insights or solutions on how to handle this scenario would be greatly appreciated!