Maintain an array with a maximum of 5 elements in MongoDB by removing the oldest element when a new one is inserted

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!

Answer №1

You are currently utilizing Mongoose instead of the Mongodb native driver.

Kindly give the code below a try and inform me of the outcome. Unfortunately, I do not have access to MongoDB for testing.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain the complete file path using JavaScript

Imagine you have a web application utilizing NodeJS and ReactJS, both working on your local machine. In this setup, NodeJS is capable of accepting files selected from the ReactJS GUI via a simple file upload feature, like so: <input type="file" id="fil ...

Refresh needed for Material UI styles to load correctly in Next JS

UPDATE: Reproducible issue https://github.com/ganavol409/next-material-ui-classes-bug Issue seems to be related to Higher Order Components and importing useStyles from Material UI Implemented Solution: https://github.com/mui-org/material-ui/blob/master/ ...

Ensuring the absence of values in deconstructed variables within an object

In my quest to efficiently destructure the end_time property from the this.props.auction object, I encountered the code snippet below. const {auction: {auction: {end_time}}} = this.props; The problem with this code is that the constant will be undefined ...

Issue with Auth0 not properly redirecting to the designated URL in a React application

auth.js import auth0 from 'auth0-js'; export default class Auth { constructor() { this.auth0 = new auth0.WebAuth({ domain: '<properURL>', clientID: '<properID>', re ...

The primary origin of TypeScript is derived from the compiled JavaScript and its corresponding source map

Being new to sourcemaps and typescript, I am faced with a project that has been compiled into a single javascript file from multiple typescript files. The files available to me are: lib.js (the compiled js code of the project) lib.js.map (the source map ...

Exploring the functionality of Async Storage in React Native for efficient data saving purposes

I'm completely new to working with Async and async storage. I am a bit lost and unsure of how to proceed, but my main objective is to use setWorkouts() to assign workouts based on the values I retrieve from asyncstorage, and then save these workouts. ...

Search for a property within a JSON object field using Mongoose

Suppose I have a schema like this: var TempSchema = new Schema({ location: Schema.Types.Mixed }); The 'location' field will store a JSON object. Now, if I want to search by a property within this JSON object field, can I use the following ...

Error in Mongodb: Unable to convert value into ObjectId

Currently, I am attempting to retrieve only the posts belonging to users using the following code snippet: router.get("/:username", async (req, res) => { try { const user = await User.findOne({ username: req.params.username }); const ...

Using JQuery to pass a concatenated variable

What is the reason behind the success of this code: $(".ab").css({'background':'#ce0000','color':'#EEE'}); While this code does not work: f("ab"); function f(ab){ var x = '".'+ ab +'"'; ...

What's the process for creating a synchronous function in AngularJS?

Is there a way to make storyboard.getAdressTimeLine run synchronously? I need storyboard.drawTimeLine to continue executing only after storyboard.getAdressTimeLine is done for (var i = 0; i < response.data.length; i++) { var obj=response.data[i]; var d ...

The requested resource at http://localhost/Grafica/%7Bd.icon%7D/ was not found (Error 404)

Creating a tooltip in a weather chart, I want to display an image of the sky condition. Below is the HTML code: <div id="tooltip"> <table class="table table-condensed"> <tr><th>Time (local)</th><th data-text="d ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

Create a JavaScript alert script devoid of any instances of double quotation marks

This snippet belongs to my webpage: <span onclick=alert('Name:$commenter_name <br>Email:$commenter_email <br> Rate:$commenter_rate <br>Comment time:$currentdate <br>Comment:$commenter_comment')>$commenter_name:$comm ...

Error Message: Module not found while using Node Express with TypeScriptIssue: A

I have set up a straightforward node express app using TypeScript. My goal is to implement an errorMiddleware in the index.ts file. As I try to start the server, I encounter the following error: at Module.require (node:internal/modules/cjs/loader:100 ...

The Array map function is not displaying the list within a React component that is based on a Class

I am having trouble displaying a list of food items in my Parent component FoodBox.js and its child component FoodItems.js. I am using the map() method, but the <ul> element is showing up empty. Here is my code for FoodBox.js const FOOD_ITEMS = [ { ...

What steps are involved in setting up the landing page for a small express application?

I have a node express server set up with the Webpack Dev Server wrapping it The express app is launched from the main directory where static files are stored in a folder named "public" Here is the configuration line: server.app.use(express.static(__dirn ...

Using the application router in Next.js to implement getServerSideProps()

I recently delved into utilizing Next.js 13 with the App Router, but encountered some challenges. The structure of my test application is as follows: ---/school ------/app ------/layout.tsx ------/page.tsx ---/src The ./app/page.tsx code snippet is ...

Tips for executing parallax designs, similar to the techniques used on the

Currently, I am in the process of creating a website that utilizes parallax scrolling. Here is a brief overview of what I have accomplished thus far. I decided to use the skrollr plugin to achieve the desired parallax effect. Through this plugin, I was abl ...

Instructions for implementing a Back button that takes you directly to the text or link you clicked on to view an image

My goal is to have multiple anchor links within text, each linking to a specific image on the same page. Once the user views the image, I want them to be able to click a 'Back' button that will take them back to where they left off in the text. ...

DOMException: Access to property "apply" on a cross-origin object has been denied

Over the last day, I've been tackling the FreeCodeCamp assignment "quote machine". Everything is working fine except for the tweet button. You can tweet as many times as you like for one single quote, but not for multiple quotes (once you tweet one, y ...