Mongoose: Guaranteeing that the array will never surpass a specific limit of items

Struggling to understand the proper syntax for a set operation in Mongoose. My schema is structured like this:

const userSchema = mongoose.Schema({
  instagram: {
    images: [{
      id: { type: String },
      media_type: { type: String },
      media_url: { type: String },
      timestamp: { type: Date }
    }]
  }
});

I need to regularly update this array with the most recent Instagram photos from the user:

User.findOneAndUpdate({ _id }, { $addToSet: { "instagram.images": { $each: arr } } });

How can I ensure that the array always contains the latest images, but never goes over 30 images? Ideally, if there are 20 images in the array and 11 new ones need to be added, all 11 new images should be appended while removing the oldest existing image.

Answer №1

To achieve this specific task, the $addToSet operator will not suffice. You have two viable options available:

  1. If you want to ensure that only unique images are fetched, you can utilize the combination of $push along with the $slice operator.
User.findOneAndUpdate({ _id }, 
    { $push: { "instagram.images": { $each: arr, $slice: -30 } } });
  1. In cases where unique images cannot be guaranteed, you need to retrieve the user data and filter the array in your code prior to updating:
let user = User.findOne({_id});
// Use a unique identifier for image uniqueness
let imagesIds = user.instagram.images.map(v => v.id);
let filteredImages = arr.filter((elem => !imagesIds.includes(elem.id)));

Finally, apply the approach from option 1 using filteredImages:

User.findOneAndUpdate({ _id }, 
    { $push: { "instagram.images": { $each: filteredImages, $slice: -30 } } });

It's important to note that mongoose typically generates an _id field for nested objects automatically, making the utility of $addToSet somewhat redundant in this context.

Answer №2

If you follow the reasoning correctly, consider using the $size operator in this way:

const T = async () => {
  try {
     //If the array_field has more than 30 elements, the result document will not be found.
     let result = User.findOneAndUpdate({$expr: {$lte: [{$size: "$array_field"}, 30]}});
     if (!result) {
        //No documents meet the criteria
     } else {
       //You can add elements using a for loop, for example
       result.array_field.addToSet(element)
       //You can also check the length of array_field before saving it
       await result.save()
     }
  } catch (e) {
    console.error(e)
  }
}

If the array_field has less than 30 elements, it will be found and updated. You can also use $size in combination with comparison operators: $gte / $lte

$addToSet ensures that you update the array with unique values. You can verify this again before saving to the collection.

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

The character is having trouble displaying correctly in the ajax response

I've been searching for solutions but nothing seems to help. The issue I'm facing is with reading characters from an AJAX response. How can I properly read characters that are coming from an AJAX response in the form of a JSON object? ["label" ...

Having difficulty sending ajax to the controller function

Currently, I am facing an issue with updating my database using AJAX in Laravel. The goal is to change the value in the enable column from 1 to 0 when a toggle button is clicked. Below script is included in the view: $(".toggle-btn").change(function() { ...

Tips for utilizing an array within React and transforming it into a component

I've developed a website that pulls data from a SQL database I created, containing details such as name, address, and occupation of individuals. I successfully managed to showcase this information on the webpage by structuring an array and inserting t ...

Encountering errors with passport-google-oauth20: InternalOAuthError arises when fetching user profile fails and attempting to set headers after they have already been sent to the client

When using passport strategies for various social media logins, I encountered the following two errors: InternalOAuthError: Failed to fetch user profile Cannot set headers after they are sent to the client I suspect that I may have returned a callback or ...

Transform JSX into JSON or a string, then reverse the process

I am looking to store the state of a React Component in a database. Json.stringify(myComponent); However, when I attempt to reuse the component using JSON.parse, I encounter Error: Objects are not valid as a React child (found: object with keys {type, k ...

Using setInterval with Vue.js computed properties

Welcome to the world of Vue js! I'm currently working with some code in Para.vue that looks like this: Para.vue <template> <t-row> <t-col :span="13"> <t-input :id="id+'_tam'" ref="tam" ...

development session not persisting on local server (localhost:4200)

Currently, I am utilizing angular for the frontend and node.js along with express for the backend of my application. The interesting observation is that when I run the app on localhost:3000 (the designated port for the express app), everything operates cor ...

Move through different screens using React JS

Can anyone help me with this issue I'm facing in React Js? I am trying to implement a button that changes to another screen when clicked, but I keep getting an error message: TypeError: Cannot read property 'push' of undefined. I have tried ...

Remove user from firebase with Admin SDK

I need help understanding how to remove a user from my admin panel using the Firebase Admin SDK. When attempting to delete a user, I encountered this error: Uncaught (in promise) ReferenceError: uid is not defined at eval (ManageCustomer. ...

What is the reason for Backbone including model details within {model: {model_property: value,...}} when saving a model?

I am currently developing an application using node.js and backbone.js. However, I have encountered an issue where saving a model results in the JSON being nested inside a model dictionary. node = new NodeModel({prop1:"value1", prop2:"value2"}); node.save ...

Tips for extracting the team member field value, which is a classification in Sitefinity 12 web services, through the use of OData and JavaScript

Utilizing ajax to retrieve data from web services in sitefinity, I have been able to successfully retrieve team member information using this specific apiURL: localhost/api/lawyerswebservice/teammembers?$expand=RelatedTeam,PrimaryImage; However, I have e ...

How can I retrieve the data from a MongoDB collection based on a particular date range using the "utc_timestamp" field?

Here is my inquiry that has two parts: I am looking to retrieve data from MongoDB based on a specified date range (start date and end date). Additionally, I would like to obtain data on a daily basis from my collection within the given date range. view ...

Unable to retrieve an item from an array while simultaneously retrieving a value from its nested array

In the document provided below- { "_id": { "$oid": "61fb6bf71be79c03227d6bbf" }, "id": "17202155", "completed": ["cse331", "cse312"], "incompleted": ...

The program detected an unfamiliar command named 'node_modules', which is not recognized as an internal or external command, operable program, or batch file

I have integrated gulp into my project. Successfully installed gulp Added the npm script Executed the script using "npm start" Encountered the following error:- **> start node_modules/.bin/gulp watch 'node_modules' is not recognized as an ...

The issue arises when creating a button source code on Gatsby and Stripe, resulting in an error message: "Uncaught TypeError: Cannot read property 'configure' of undefined."

I've been working on developing an e-commerce platform following a tutorial I found here. However, when I check the source code for checkout.js, it throws these errors and the entire page becomes blank. Uncaught TypeError: Cannot read property &apos ...

Trouble presenting information retrieved from API

I'm encountering an issue with displaying the data I fetched from an API. I'm not sure what's causing the problem... I attempted to use the map() function to access the data, but it's not functioning as expected either. import React fr ...

What is the correct way to insert information into a specific collection using pymongo?

How can I insert data into the correct collection by name? The code snippet provided seems to be working well. The function collections(db, name) returns the name of the collection based on the input. However, when I try to save the collection name using ...

A simple guide on how to surround every incorrect input index in mapped inputs with red borders

I am incorporating a modal that corresponds each element of the object newCompanies to a specific row: {newCompanies.map((company, index) => { return ( <div> <div className="side- ...

Encountered an error message stating "This dependency was not found" after installing a package using npm

I recently added a package called htmldiff to my Vue project using the npm install command. The next step was to try importing the package into one of my components. import { diff } from 'htmldiff'; // note that the package does not use default ...

JavaScript design not aligning

I'm currently attempting to find a pattern that includes the pipe (|) operator. Here is the code I've used to match the pattern: var format = /[ \\|]/; // This is the pattern for matching the pipe pattern if ("Near raghavendra temple ...