Manipulate a nested array in Mongoose: Modifying an object within

Here is my MongoDB schema structure, which includes a nested array of flashcards inside subjects:

const classrooms = new mongoose.Schema({
    name: String,
    year: String,
    student: [
        {
            firstname: String,
            lastname: String,
            mail: String,
            userId: String,
        }
    ],
    subject: [
        {
            subjectId: String,
            flashcard: [
                {
                    title: String,
                    tag: []
                }
            ]
        }
    ]
});

I am trying to update a specific flashcard object within a subject array using the following code snippet:

const flashcard = await classroomModel.findOneAndUpdate({
    _id : classroomId,
    "subject" : {
        "subjectId" : subjectId,
        "subject.flashcard" : {
            "_id" : flashcardId
        }
    },
    "$set" : {
        "flashcard.title" : "new title"
    }
})

However, I'm facing an issue where all flashcards within the object are getting deleted. Any guidance on this matter would be highly appreciated.

Answer №1

To update the flashcard document based on specific criteria for both subject and flashcard, you must utilize arrayFilters.

db.collection.update({
  _id: 1//classroomId,
  
},
{
  "$set": {
    "subject.$[subject].flashcard.$[flashcard].title": "new title"
  }
},
{
  arrayFilters: [
    {
      "subject.subjectId": 1//subjectId
      
    },
    {
      "flashcard._id": 1//flashcardId
      
    }
  ]
})

Explore Sample Mongo Playground

Answer №2

After considering the suggestion from @yong shun as the preferred method, here is an alternative approach for those who are not fond of mongoose syntax:


      const classroom = await classroomModel.findOne(
        {
          _id: 1 //classroomId,
        },
      )

      const subject = classroom.subject.find(
        (currentSubject: any) => {
          return currentSubject.subjectId == 1 //subjectId
        }
      )

      const flashcard = subject.flashcard.find(
        (currentFlashcard: any) => {
          return currentFlashcard._id == 1 //flashcardId
        }
      )
      flashcard.title = "my new title";
      await classroomModel.updateOne(classroom);

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

Displaying AJAX data in Django using an HTML table

My Django template currently has the following AJAX script running: function create_table() { $.ajax({ method: "GET", url: "/api/data/", success: function(data){ console.log('button clicked') ...

Having difficulty encoding Uint8 ArrayBuffer (of an image) into a base64 buffer for storage in a Mongo database

Currently, I am attempting to download an image from a URL provided by the client-side on the server side and then store it in a MongoDB database. router.post('/fetchbyurl'), async (req,res) => { const mime = require('mime-kind') ...

A real-time countdown timer that dynamically updates based on incoming data from a WebSocket connection

I'm looking to create a unique 10-second JQuery Countdown Timer that integrates with a WebSocket for real-time updates. The timer should reset based on data received from the WebSocket and start over if new data is received, only affecting that specif ...

Is there a way to prevent the omission of zeros at the end in JavaScript when using Number.toString(2)?

I am facing an issue while trying to reverse a 32-bit unsigned integer by converting it to a string first. The toString(2) function is causing the zeros at the end to be omitted, leading to incorrect output. This is my code: var reverseBits = function(n) ...

Is there a way to substitute a string that is connected to another string?

When extracting a long description from a data source, it often exceeds 5,000 characters. In order to display a concise version, we utilize a one-line description field that is optional. If left empty, we take the first 128 characters of the description an ...

Effortless scrolling implementation

How can I make the scroll smooth and animated with this code structure? Check out my JSFiddle here: https://jsfiddle.net/v7qhzo8q/ The code structure is as follows: <nav id="nav"> <ul id="top"> <li><a href="#">Home</a> ...

Angular JS Form's Pristine feature is malfunctioning when attempting to reset

I implemented a login form on my website. After submitting the form, I clear it and set it to Pristine mode. However, the error message still persists. Below is the code for my form: <form name="loginForm" ng-submit="loginForm.$valid && login( ...

Fabric.js Textbox does not automatically wrap long text in version 5.3.0

I am currently using fabric.js version 5.3.0. The Textbox object in fabric.js will wrap text when you add space between words, but it won't wrap when you add text without any spaces. Please take a look at the following fiddle: https://jsfiddle.net/N ...

Selecting the first li element using JQuery selectors

Can anyone help me with creating an onclick event that triggers when the user clicks on the first list item which is labeled as "Any Date"? I am looking to use jQuery to target this specific element. <ul id="ui-id-1" class="ui-menu ui-widget ui-widge ...

I am in the process of creating a dropdown menu for a navbar that will appear when the cursor hovers over a specific element, complete with an arrow pointing upwards

In my current project with NextJS and Tailwind CSS, I've successfully created a dropdown menu but I'm facing an issue with positioning the arrow to point to the specific element being hovered on. In a previous version, I tried rotating a div at 4 ...

Exploring Sankey Color Schemes in Apache ECharts

In my Angular app, I am working with a sankey chart and exploring different chart options. Here is the current implementation: this.chartOptions = { color: ["#922752", "#ff9822", "#4390e1", "#53bcbc"], tooltip: { ...

Changing letter cases in a textbox using Javascript

I have a challenge to create a code that can switch the case of text entered by the user. Here is what I currently have: var num; function toggleTextCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase( ...

What is the best method to deactivate additional choices and add inputs to several dropdown menus containing identical values using angular js?

Would like to have 3 dropdown lists with identical values. The first dropdown must be selected, while the other two are optional. All three dropdowns will have the same options. If a user selects an option in dropdown 1, it will become disabled for the re ...

Generating a pdf Blob from an array and displaying it

I am encountering an issue with displaying my PDF file. The data is coming as a byte array, and this is how I currently have it set up: // data is initially String {0: % 1:P 2:D ...} const byteArray = _.map(data); // ["%", "P", "D", "F", "-", "1", ...

Save the data from the input form into a JSON file

I'm new to using Express and I want to store the input field value in my JSON file. When I try to do this, I get an error message: POST http://localhost:5500/userData 405 (Method Not Allowed). From what I understand, it seems like the server is not su ...

The modal form vanishes without any action when the form is clicked outside

Everything was working fine with the form submission until I turned it into a modal using Bootstrap. Now, when the form is rendered in the modal, users can tab and type without any issues. However, if they click on any element within the modal (including t ...

use jsreport to output to a writable stream

My goal is to have jsreport write to a writablestream. When I print the buffer in the writablestream, I receive a PDF description. However, when I try to save it to a PDF file, I encounter an error stating that the file is corrupted. function streamtoPdf( ...

Changing the file path names for two images simultaneously within a single ExpressJS route

What is my current task :: I am working on an expressjs program that is responsible for moving the image from temp location to /public/images/ for a single image. The key name for the image is :: key I am using :: var file_name=req.files.key.originalF ...

Obtain the Text Content from a Knockout Dropdown Menu

Currently, I am facing an issue with extracting the text value of a selected option from a dropdown menu on my webpage. The dropdown contains various image categories and is defined as follows: <select class="form-control" data-bind="options: imageCate ...

Learn techniques for recognizing React components by utilizing the inInView hook and transmitting their values to a child component

Currently, I am working on creating a navigation bar using React that dynamically highlights the active component when it is scrolled into view by the user. For example, if the user scrolls to the 'About' section, the user icon should be highligh ...