Updating a key in an array of objects with Mongoose in real-time

Although this question may have come up before, I haven't been able to find a solution that works.

Essentially, I have an array of objects containing Boolean data and I want to be able to update these objects dynamically using my API routes/logic.

Data Example:

{
    "_id": 1,
    "posts": [
       { "_id": d323d32, "published": true, "homepage": false, (...moreBooleanData) }, 
       { "_id": ffwfwfwc, "published": true, "homepage": false, (...moreBooleanData) },
       { "_id": fdscsdad, "published": true, "homepage": false, (...moreBooleanData) }
    ]
}

Mongoose Query

await Project.findOneAndUpdate(
    { _id: 1 },
    { $set: { "posts.$[el].published": isChecked } },
    {
        arrayFilters: [{ "el._id": postid }],
        new: true
    }
)

The issue lies in the line

"posts.$[el].published": isChecked
. Instead of hardcoding the key published, I want it to be dynamic so that I can retrieve it from the body of my post request.

const { DYNAMIC_KEY , isChecked } = req.body

"posts.$[el].$[DYNAMIC_KEY]": isChecked`

I've attempted various methods such as using backticks for the $set string and building it outside the query, but none have been successful. Any suggestions?

Answer №1

To implement this functionality, you can utilize bracket notation:

router.post("/project/:id/:postid", async (req, res) => {

  const { isChecked, dynamicKey } = req.body;
  let set = `posts.$[el].${dynamicKey}`;

  console.log(set);

  const result = await Project.findOneAndUpdate(
    { _id: req.params.id },
    { $set: { [set]: isChecked } },
    {
      arrayFilters: [{ "el._id": req.params.postid }],
      new: true
    }
  );

  res.send(result);
});

In the project document, there are 3 posts as follows:

{
    "_id" : ObjectId("5def81070066dc23e05b816e"),
    "posts" : [
        {
            "_id" : ObjectId("5def81070066dc23e05b8171"),
            "published" : true,
            "homepage" : false
        },
        {
            "_id" : ObjectId("5def81070066dc23e05b8170"),
            "published" : true,
            "homepage" : false
        },
        {
            "_id" : ObjectId("5def81070066dc23e05b816f"),
            "published" : true,
            "homepage" : false
        }
    ],
    "__v" : 0
}

A post request is sent to the router

../project/5def81070066dc23e05b816e/5def81070066dc23e05b8170
with the provided body:

{
  "isChecked": false,
  "dynamicKey": "published"
}

The updated result would look like this: (The published value of the post with id 5def81070066dc23e05b8170 is now false)

{
    "_id": "5def81070066dc23e05b816e",
    "posts": [
        {
            "_id": "5def81070066dc23e05b8171",
            "published": true,
            "homepage": false
        },
        {
            "_id": "5def81070066dc23e05b8170",
            "published": false,
            "homepage": false
        },
        {
            "_id": "5def81070066dc23e05b816f",
            "published": true,
            "homepage": false
        }
    ],
    "__v": 0
}

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

Using JQuery to monitor the loading of a newly selected image src attribute

As a newcomer to JavaScript and JQuery, I am facing a challenge that I couldn't find a solution for in other discussions: I have a function that retrieves the path to an image (/API/currentImage) using a GET request and needs to update the src attrib ...

Can you explain the function of mdLiveAnnouncer in Angular Material and how it operates?

Could someone provide an explanation of $mdLiveAnnouncer using this code snippet? module.controller('AppCtrl', function($mdLiveAnnouncer) { // Making a basic announcement (Polite Mode) $mdLiveAnnouncer.announce('Hey Google'); // ...

How can I retrieve the value of a radio button using jQuery

My goal is to retrieve the selected/checked radio button value using the .get function. I believe my code is correct, but the sequence seems to be off. $.get('burgerorder_check.php', function(data) { inputVal = $('input[type ...

What is the proper way to use jQuery to append the value of the variable 'valCookie' to an array?

Is there a way to store the indexes of clicked elements in an array and save the state of a menu using cookies? How can I efficiently handle variable data in an array? $(document).ready(function() { //index array var indArray = []; var indToCook ...

Removing a nested field within an array in MongoDB

I have data stored in a MongoDB database that is structured as follows: { "parserErgebnis": [ { "values": { "prop1": { "status": "OK", "wert" ...

Updating the image source through ajax by retrieving the location from the database

Is there a way to dynamically change the image source using AJAX? I have the location saved in my database and I want to set the img src from the value of something like data[0]['patient_photo']. Below is the HTML code for the image: <img id= ...

Execute a query to retrieve a list of names and convert it to JSON using Unicode encoding in

Just starting out with Laravel and I'm trying to figure out how to execute some queries Not talking about the usual select statements... I need to run this specific query: SET NAMES 'utf8' First question, here we go: I have Hebrew ...

Mongoose schema nesting guide

I've encountered an issue while attempting to nest schemas in mongoose, and unfortunately I'm struggling to pinpoint the exact cause. Here's what my current setup looks like. Starting with the parent schema: const Comment = require("./Comm ...

The ability to submit a conversation chat is currently

I encountered an issue when attempting to submit a chat, and I received the error message 'handlebar is not define'. I followed the code tutorial provided in this link: https://codepen.io/drehimself/pen/KdXwxR This is the screenshot of the error ...

Embed a website in an iframe and modify a portion of the URL within the embedded page

Welcome to my first question here! I am looking for a solution that will allow me to load a webpage inside an iframe while modifying parts of the URLs in any links on the page with different text. For example, let's say we load a website like "myweb ...

Struggling to dynamically append additional textboxes to a <div> element using JavaScript

After spending over 12 hours on this problem, I am completely stuck and frustrated. I have tried countless variations and sought out other solutions to no avail. It should be a simple task. My project involves using JQueryMobile 1.2 along with its dependen ...

HighCharts velocity gauge inquiry

I recently integrated a highcharts speedometer with PHP and MYSQL on my website. Everything seemed to be working smoothly until I added the JavaScript code for the speedometer, causing it not to display. There are no error messages, just a blank screen whe ...

Implementation of the render function in a Node Express class

I've been working on a class with methods to retrieve domains from an API, and everything has been functioning correctly up until I tried to render it using Node Express. When I attempt to display the data, all I get is an array of numbers without the ...

Mastering the use of getText() in Protractor with Page Object Model in Javascript

Having trouble retrieving specific values from my page object. The getText() method is returning the entire object instead of just the text, likely due to it being a Promise. I can provide my code if necessary, but I'm aiming to achieve something sim ...

Javascript function for downloading files compatible with multiple browsers

When working with a json response on the client side to build content for an html table, I encountered an issue with saving the file to the local disk upon clicking a download button. The csvContent is generated dynamically from the json response. Here&ap ...

Transform the default WordPress gallery into a stunning slideshow with FlexSlider 2 integration

Greetings, I am searching for a solution to modify the default WordPress gallery in order to integrate the FlexSlider 2 plugin. I specifically want to incorporate this module or feature from this link, but I have been unable to figure it out myself. Your ...

Is it possible to use setState after a setTimeout to unmount a component?

Can anyone help me find the issue with my code? I am attempting to clear an error message after a specific duration, but it's not working as expected. I'm puzzled about what might be causing this problem. export default class MyError extends Com ...

Looping to run an async process (sequilize.authenticate) multiple times until successful

I need my microservice to wait for the database to become available before proceeding. There is a sidecar Cloud SQL proxy involved that requires some time for the database connection. My current approach involves a for loop that retries connecting after a ...

What is the process to include an image file in a JSON object using PhoneGap?

Having trouble saving an image in JSON. Managed to access the mobile camera with the provided code: var pictureSource; // source of the picture var destinationType; // sets the format of returned value // Wait for PhoneGap to connect with the device / ...

Mastering the art of navigating through intricate nested properties within JSON data structures

Presented below is a dynamic JSON structure: data = { "name": "deltha", "type": "object", "important": [ "name", "id", "number" ], "information": { "place": { "editable": false, "visible": true }, "info": { ...