Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry.

Here is the code from controller.js:

const updateSubCategory = asyncHandler(async (req, res) => {
  const {
    dataArray
  } = req.body

  const categories = await Category.find({})

  if (categories) {
    await Category.updateOne({
      "SubCats._id": req.params.id
    }, {
      "$set": {
        SubCats: {
          name: dataArray[0],
          image: dataArray[1]
        }
      }
    }, {
      "multi": true
    })
    res.json({
      message: 'sub-category updated'
    })
  } else {
    res.status(404)
    throw new Error('Error')
  }
})

Answer №1

It appears that you may require this solution, though I cannot be certain. If you find it unnecessary, please provide sample data and the desired output in JSON format.

For a demonstration, you can check out PlayMongo. This tool allows you to update specific fields without replacing the entire embedded document, unlike your current query.

const updateSubCategory = asyncHandler(async (req, res) => {
  const {
    dataArray
  } = req.body

  const categories = await Category.find({})

  if (categories) {
    await Category.updateOne({
      "SubCats._id": req.params.id
    }, {
      "$set": {
        "SubCats.name" : dataArray[0],
        "SubCats.image" : dataArray[1]
        }
      }
    }, {
      "multi": true
    })
    res.json({
      message: 'sub-category updated'
    })
  } else {
    res.status(404)
    throw new Error('Error')
  }
})

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

What is the best way to transfer the $http response value to another function?

I currently have these two functions set up. One function, $scope.submit, handles posting data to the server and capturing the response value. The other function, $scope.addTeams, is responsible for adding teams based on the response from $scope.submit. ...

Is there a way to trigger $q notify without initiating a $digest cycle?

Within my application, the $digest cycle typically takes around 5ms to complete. I heavily utilize $q.defer with deferred.notify throughout my codebase, but I've encountered an issue. Each time deferred.notify is triggered, it schedules a new digest c ...

Is there a way to activate and change the color of a Radio Button when it is clicked?

Is there a way to change the background-color of a clicked Radio Button so it appears highlighted? For example, when the first choice is clicked, I want it to stand out visually. This is the current UI displaying the choices: https://i.stack.imgur.com/a7 ...

Is it possible for an animation to complete even if it is stopped midway?

I am currently working on a media player project where I have implemented a scrolling marquee effect for the song meta information using JavaScript and CSS. The scrolling effect only occurs when the track is playing, and I achieve this by adding/removing ...

Mongoose documents are set to automatically be deleted after a duration of one month

My goal is to retain a particular document for one month after the client-user deletes it. To achieve this, I have decided to simulate a delete action and display data in the browser. Sample schema: const product = new mongoose.Schema({ --- trash : { ty ...

Managing AJAX Errors in PHPAJAX error handling tips for developers

My current code is only set up to display a general error message when an error occurs during execution. I want to improve it by returning specific error messages for different scenarios. However, I have not been able to find satisfactory solutions in my s ...

"Experiencing a problem with Next.js 13 where the User Context is not functioning properly outside of _app

When using Next.js 13 and the user context, I've noticed that it doesn't function properly outside of _app.tsx. Any idea why? src>context>UserPositionContext.tsx import { createContext, useContext, useState } from "react"; const ...

What could be causing my express router.get endpoints with multiple paths to only render text?

Currently, I am in the process of configuring a password reset flow using Pug (formerly Jade) and Express. Oddly enough, GET requests that contain URLs with multiple appended paths are causing my Pug view files to render with only text. The images and sty ...

Prevent event propagation in jQuery by using .stopPropagation() when hovering over a

When trying to implement event.stopPropagation() in a specific scenario, I encountered an issue with a blinking background image on my submenu. To address this, I added a pseudo-element (background:green) to the parent element by toggling a new class using ...

Create a complete duplicate of a Django model instance, along with all of its associated

I recently started working on a Django and Python3 project, creating a simple blog to test my skills. Within my project, I have defined two models: class Post(models.Model): post_text = models.TextField() post_likes = models.BigIntegerField() post_ ...

What strategies can be utilized to condense code when needing to adjust a className based on various props?

I am looking to condense this code, particularly the [if~else if] block, in order to dynamically change a className based on different props passed. export default function Button(props) { const { name, height, color, bgColor } = props; let className = ...

Verify whether the session has been initiated and establish a global variable that can be utilized by JavaScript

I currently have the following arrangement: main.php page.php Whenever a user visits any of these pages, they experience an "introductory header animation". However, I want to ensure that this animation is only displayed on their initial visit and not w ...

What is the best way to swap out one component for another in a design?

I am working with a component that has the selector 'app-view', and I need to replace a specific part of the template: <div> content </div> The part that needs to be replaced will be substituted with another component: selector: &a ...

Using React Native to share API and passing a Base64 string in place of an image when sharing to WhatsApp

I am facing difficulties in sharing a base64 image on WhatsApp. On both iOS and Android, the actual base 64 code is shared instead of the image. When I try to use iMessage or Email on iOS, the base64 images are converted and displayed correctly. However, ...

Ways to assign values to an array within an object

I'm attempting to transfer the contents of one array into an array within an object, but I keep encountering this error: Type 'any[]' is not assignable to type '[]'. Target allows only 0 element(s) but source may have more. Here ...

An error has been caught in the Angular JS application while using the highcharts-ng module: [$injector:modulerr]

I'm encountering an issue while trying to integrate Highcharts into my Angular/Node/Express application. I am utilizing the highcharts-ng directive available at https://github.com/pablojim/highcharts-ng Every time I run my app, I consistently receive ...

I can't figure out why I'm receiving a TypeError stating that onSuccess is not a function within my AngularJS service

Utilizing an angularjs service that utilizes restangular for API calls. angular.module('app.userService', []) .factory('userService', ['localStorageService', '$rootScope', 'Restangular', func ...

Using Ajax to poll a Celery task

I am working on a Celery task that updates a PostgreSQL database gradually. In my Django application, I want to fetch the latest data from the database and display it in a template in real-time as the task progresses. I am looking to implement this real-ti ...

Expanding Java Classes and Replacing Methods with Multiple Parameters in ES4X/Graal

I am currently facing a challenge in my JavaScript project using ES4X/Graal, where I need to extend a Java class. This Java class has methods with overloaded parameters that I must override. While I understand how to call a specific Java method by specifyi ...

What is causing the bullets for the unordered list to appear before the items are inserted into the list?

Can you explain why the bullets are showing up before the list items are added? <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>To Do List</title> </head> <body> ...