Manipulate a nested array in MongoDB with JavaScript array functions

Having trouble updating a field with mixed types in my mongoose schema. Although I acknowledge this may not be the ideal schema setup, there are specific reasons why it's structured this way. My goal is to perform array-like operations using JavaScript, such as pushing elements. Additionally, I am looking to access the index of the current document being iterated within nested arrays, specifically in the 'tags' field. Here is an example:

Mongoose Schema

let user = {
    name : String,
    email : String,
    tags : []
}

The 'tags' field is dynamically generated upon creating a user and can result in a structure like this after inserting the user into the database:

tags : [ 
        [{obj1}, {obj2}, {obj3}, ...], 
        [...], 
        [...], 
        [...], 
        [...] 
    ]

My objective is to add a new document to the nested array using traditional JavaScript methods.

user.tags[0].forEach(obj, index){
    // Perform operations here with obj and index
    // Unsure how to update a nested array using the MongoDB $push operator, resorting to 'js array push' method

    let newObj = { foo: bar }
    user.tags[0].push(newObj)
    user.save()
}

Following testing on Postman, the operation seems successful, returning the inserted item. However, I've noticed two issues:

  1. The changes are not persistent in the database, while the response in Postman shows otherwise:
{
    name : bar,
    email : foo,
    tags : [
        [{ foo : bar}], // from the last push operation performed
        [],
        [],
        []...
        ...
    ]
}
  1. Subsequent 'push' operations to any array index (e.g., 0th index) replace the current object instead of appending it: user.tags[0].push(obj) ===> this replaces the first object in the postman response, although it does not reflect in the database because the changes are not persistent

Any assistance in achieving this would be highly appreciated. I am still learning about these concepts, so alternative solutions to tackle the same problem are also welcome. Thank you! :)

Answer №1

After a long search, I finally stumbled upon the solution here: Freecodecamp forum

The missing piece was to include

user.markModified("nameOfFieldToUpdate")
before calling user.save(). Once this adjustment was made, the issue was resolved.

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

Error occurred while fetching image from Medium story API in Next.js

While working on my Next.js app, I encountered an issue with the Medium story API. Every time I try to fetch and display an image using the API, I receive an error message stating "upstream image response failed." The specific error code is: upstream image ...

React's useState feature is doubling the increment

I have created a basic form management system with a historical feature. A simplified version of this system can be seen on codesandbox import { useState } from "react"; import "./styles.css"; const sample = ["what", "w ...

Creating a WebSocket service similar to stackoverflow using Node.js: A step-by-step guide

I'm currently developing a chat application using node.js. I have implemented a feature to receive new messages via ajax, where requests are sent every 3 seconds. However, I recently observed that stackoverflow handles fetching new data differently. I ...

Creating a Chrome extension with Angular 5: A comprehensive guide

Currently, I am in the process of developing a Chrome extension using Angular 5. Initially, I successfully created a basic Angular app with the help of Angular Material and it functioned perfectly as an Angular application (I used ng build for verification ...

Tips for redirecting a port for a React production environment

I am currently setting up both Express.js and React.js applications on the same Ubuntu server. The server is a VPS running Plesk Onyx, hosting multiple virtual hosts that are accessible via port 80. To ensure these apps run continuously, I have used a too ...

Dealing with massive arrays in C++

I have recently taken over a Java codebase from a past student and am in the process of converting it to C++, a language I am more comfortable with. As I dig into the code, I'm on the lookout for areas where I can make improvements. The main issue at ...

Every time you attempt to download in Vue, you are met with the familiar sight

Encountering a peculiar issue while attempting to download an apk file using a Vue.js website: Referring to How to download a locally stored file in VueJS, I am trying to download a local file with this command: <a href="../../app-debug.apk" download= ...

What is the most effective method for cropping and uploading images using express?

Using the knox library, I have successfully uploaded an image to a S3 server through express. My goal is to allow users to crop their profile picture, similar to what Facebook offers. I am considering using Jcrop for the user interface and imagemagick fo ...

HTML string decoded incorrectly in CodeIgniter due to encoding error

When I send data that includes an HTML string along with other information from JavaScript to the PHP (Codeigniter) server using AJAX and JSON, I notice that the style information within the HTML string is missing once it reaches the server. Everything els ...

FETCH user details quickly

Greetings! My goal is to implement a feature where a user can be passed into a GET request to view the items they have posted. Below is the structure of the GET request: // @route GET with NAME // @desc GET All ITEMS WITH NAME // @access private route ...

Create new instances of Backbone Models using an existing Backbone Model as a template

Within my app, I am planning to include a configuration file called config.json as a Backbone Model. Here is an example of how it will be loaded: var Config = Backbone.Model.extend({ defaults: { base: '' }, url: 'config. ...

JavaScript function unable to execute form action properly

I have a link RESET YEAR which triggers a servlet to check if the current year is equal to the present year. If they are not equal, then the function resetyear() is supposed to be called. The issue I am facing is that the function is not working as expecte ...

Uploading an array to SQL Server and MySQL databases with C# .NET

In my Winforms application using C#, I am working with a List: List<string> StudentSubjects = new List<>(string); These are the subjects I have inserted into the List: StudentSubjects.Add("Physics", "Chemistry", "Mathematics", "English"); ...

How to store data retrieved with $http.get in AngularJS into a variable

I am attempting to assign data retrieved from $http.get to a variable in my controller. $http.get(URL).success(function (data) { $scope.results = data; console.log('results within $http.get :'+ $scope.results); }); console.lo ...

Discover the exact location of an HTML element within an iframe

I am currently attempting to determine the position of an element that is within an iframe. I have written the following code for this purpose: // Custom function to calculate the position of an element on the page function getElementPosition(elem){ var ...

Adding graphs dynamically to Dygraphs allows for real-time updates and interactive data

I recently started using Dygraphs for one of my projects and I am still learning how to work with it. After reading through the documentation and looking at a few examples, I noticed that the constructor for Dygraphs requires a div element where the graph ...

Mastering ExpressJS Routes for Advanced Functionality

Creating an express route that will match both /users/joe /users/joe-4574 It has been a challenge for me to find the correct regular expression to solve this. Despite trying various combinations, I have not been successful in getting it to work. Import ...

How can I divide the items in a Java list?

I am attempting to separate the individual elements of a String[] array. The elements in the array are as follows: {"0 1 0 1", "0 0 1 1", "1 1 0 1",...}. My goal is to split each element using the regex " " (a single space). Will this action transform t ...

What is the method to include a CoffeeScript file in my project?

Currently, I am attempting to follow the steps outlined in this CoffeScript tutorial. After opening the terminal and navigating to the directory where simpleMath.coffee is located, I proceeded to run node and entered var SimpleMath = require('./simpl ...

adjusting the color of ion-button when hovering over the cancel button

I'm working on a button bar for my app and I want the color of the button to change based on its state (false, true). Currently, the button starts out green, turns light green when hovered over, and becomes white when clicked. Once I click it, the bu ...