Locating and updating a subdocument within an array in a mongoose schema

Here is the mongoose schema I created:

The userId is a unique number that Okta generates for user profiles.

var book_listSchema = new mongoose.Schema({

userId:{type: String, required: true},
first_name: { type: String, required: true},
last_name:{ type: String, required: true},
newList: [{

         list_name: String,
         books:
    [{
        book_name: {type: String, required: true},
        book_author: {type: String, required: true},
        date_added: {type: Date, default: Date.now},
        date_finished: {type: Date, default: Date.now},

    }]}],

});

Below is the code snippet I'm using to find and update, specifically adding a book to the books array.

'''
book_list.findOneAndUpdate({"userId": req.userContext.userinfo.sub, newList:{"newList.list_name": list_name}}, {$push:{books:{book_name: title, book_author:author, date_added: new Date()}}}

'''

However, I am facing an issue where the books array does not get updated correctly. Each object in newList has a list_name associated with different lists, each containing their own books array. Therefore, it's essential to ensure the correct list is being updated when a new book is added.

For reference, here is a sample dataset:

'''
            _id:625c81d7622b044fb297ce54

             userId:"00uvgyn7OikAwud6"
             first_name:"John"
             last_name:"Smith"
             newList:Array
                 0:Object
                   list_name:"read"
                   books:Array
                      0:Object
                      book_name:"The Great Gatsby"
                      book_author:"Francis Scott Fitzgerald"
                      date_added:2022-04-19T00:43:24.248+00:00
                     _id:625e05ac083663dc44f37804
                    date_finished:2022-04-19T00:43:24.252+00:00
                    _id:625e05ac083663dc44f37803
                    __v:0
 '''

Answer №1

Make sure to follow the correct approach:

db.collection.update({
  userId: "00uvgyn7OikAwud6",
  newList: {
    $elemMatch: {
      list_name: "read"
    }
  }
},
{
  $push: {
    "newList.$.books": {
      book_name: "a new book",
      book_author: "some author",
      date_added: new Date()
    }
  }
})

Alternatively, you can use your own code snippet:

db.collection.update({
  userId: req.userContext.userinfo.sub,
  newList: {
    $elemMatch: {
      list_name: list_name
    }
  }
},
{
  $push: {
    "newList.$.books": {
      book_name: title,
      book_author: author,
      date_added: new Date()
    }
  }
})

By using $elemMatch, you can match multiple components within the array element and then apply $push to insert the specific object in the array.

You can test the query here: https://mongoplayground.net/p/YnzDRfhwpEt

For more information on $elemMatch, refer to this link.

If you encounter any issues, feel free to reach out for assistance.

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

Failure of Angular to execute HTTP calls asynchronously

I am feeling a bit perplexed about how and when to use the .then and/or .success functions. Here is a function example: $scope.handleData = function(option){ if(option == 1){ link = firstLink/; }else{ link = secondLink/; } ...

Ensuring the timely execution of Javascript functions with Selenium before moving on

While working on creating test cases using Selenium, I encountered an issue. In one of my test cases, there is a small form and a search button on the website I'm testing. Filling the form and clicking the button are not the problem. The issue arises ...

Unable to utilize Bower due to a node.js malfunction

Currently facing an issue while attempting to utilize bower for installing all necessary components for my website project. Each time I make an attempt, the following error presents itself: TypeError: Object #<Object> has no method 'toLowerCase ...

What is the process for transforming this information into JSON format with Javascript?

I have a server response with data that needs to be converted to JSON using JavaScript. country=Philippines\r\n countryid=840\r\n operator=Globe Telecom Philippines\r\n operatorid=246\r\n connection_status=100\ ...

Anticipating the issue: Strategies for minimizing nested callback functions in Node.js with Express

Recently I have been delving into the world of node.js, specifically using Express to create a basic website integrated with a MySql database. I've followed the standard application structure provided by Express (which is not relevant to my query). I ...

Place an image at the center with a height set to 100% within a div that has a fixed height and

Apologies for asking about this topic again, but I have been unable to find a solution where the image fills 100% of the height. If you'd like to see the issue in action, here's a link to the jsfiddle: http://jsfiddle.net/BBQvd/3/ I'm just ...

Having Trouble Assigning a Value to a Dropdown Menu in AngularJS

I am working with a DropDown feature where I am using ng-repeat to bind values to the options. My goal is to set the selected value based on the 'value' field only. Below is the code snippet: <div ng-controller="myCtrl"> <select ng ...

Eliminate redundant tags using jQuery

I have a code snippet that I need help with. I want to check for duplicates and if found, display an alert stating that it already exists so users can't insert the same word/tag again. Can someone please assist me? <div id="tags"> <span>a ...

Detecting whether a browser is capable of supporting dark mode

One method to determine if dark mode is active is by using prefers-color-scheme: dark: const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; Is there a way to detect if a browser supports dark mode as well? (By "supports ...

Remove data from a database using Ajax in ASP.NET MVC without utilizing DataTables

I'm encountering a slight issue with my code. I am attempting to delete a row from the database without using DataTables in ASP.NET MVC, but it seems to be not working as expected. I have displayed all items from the database on a page within div elem ...

Executing a jQuery AJAX function when the timeout occurs

My goal is to dynamically reload my jQuery DataTables without having to refresh the entire page in order to fetch new data. Here's the initial function I have set up to kick off the process: $(document).ready(function() { $.ajax({ url:&apo ...

What methods can we employ to prevent the GraphQL query from being triggered with every keystroke when using React?

Recently, I received a new task that requires me to implement input value debouncing to prevent backend requests on every keystroke. Additionally, I need to establish an internal useState for CollectionsAutocomplete, which is connected to the generalQuery ...

Uninstall all packages that are no longer listed in the package.json file using Npm

Seeking guidance on how to uninstall packages from the node_modules directory that are no longer listed in package.json. These packages were removed by another developer and the package.json file has been updated on git. Any tips on how to accomplish this ...

Ways to merge several getServerSideProps functions

Within my project, I have two important pages: index.js and other.js. In index.js, there exists a crucial method known as getServerSideProps: export async function getServerSideProps(context) { //code here } The challenge arises when I realize that I ...

Ways to center your attention on the Textbox

I am currently developing a chat program using JavaScript, HTML, and CSS. How can I set the focus on the input field for typing messages? Is it usually done with CSS code? Here is the current CSS styling for my message input field: Code: #messageField ...

Using both Promise based architecture and events in Node.js can lead to unexpected behavior and should be avoided

Currently, I am developing a nodejs application that is expected to grow in size. Despite my efforts, I have not been able to find many resources on advanced Nodejs project architecture and structure. I am wondering if it would be considered bad practice ...

Ways to display multiple PHP pages in a single division

Within my project, I have a unique setup involving three distinct PHP pages. The first file contains two divisions - one for hyperlinked URLs and the other for displaying the output of the clicked URL. Here is an excerpt from the code snippet: <script& ...

Leveraging the power of $lookup and $mergeObjects in aggregation

I'm looking to join a collection. Previously, I used only lookup to get separated fields that are joined, but now I need the results similar to MySQL join. I have tried using $lookup and $mergeObjects for this action, but they are not working well. H ...

How to make an entire video clickable on Android for seamless playback?

I have implemented an HTML5 video in my mobile web application. Currently, users need to click the small play icon at the bottom left of the video to start playing it. Is there a way to make the entire video clickable so it plays when clicked anywhere on t ...

Ways to include a new data in an array using Mongoose

In order to retrieve the defaultAccountId and present it to the user, I must check if there is a different defaultAccountId associated with the same email and password. If there is, I need to append that additional defaultAccountId to the buisnessUnit ar ...