Add an item to a nested array of objects inside a mongoose array of objects

I'm struggling to insert an object into an array of components. The components array is nested in a "scenes" array within a projects object. Below is the faulty route and a representation of the projects model, illustrating where all the fields are located. I've spent hours trying to pinpoint the problem without success.

{
        "_id": {
            "$oid": "5c01c26ec028296289f53b00"
        },
        "update": false,
        "publishStatus": "draft",
        "user": {
            "$oid": "5bee30aed343c30016a664b5"
        },
        "projectName": "Griffith Uni",
        "description": "sdaidjasidjasidjiasdjsad",
        "scenes": [
            {
                "_id": {
                    "$oid": "5c01c29dc028296289f53b02"
                },
                "sceneName": "Persona Choose",
                "components": []
            },
            {
                "_id": {
                    "$oid": "5c01c2acc028296289f53b04"
                },
                "sceneName": "Home Menu",
                "components": []
            },
            {
                "_id": {
                    "$oid": "5c0208b16c550072b6b3b499"
                },
                "sceneName": "The Smiths",
                "components": []
            }
        ],
        "lastUpdated": {
            "$date": "2018-11-30T23:06:22.173Z"
        },
        "__v": 0
    }

    router.post(
        "/projects/scenes/components/new",
        passport.authenticate("jwt", { session: false }),
        (req, res) => {
            const newComp = new Components({
                content: req.body.content
            });
            Project.findById(
                { _id: req.body.projectID },
                Project.findByIdAndUpdate(
                    { _id: req.body.sceneID },
                    { $push: { components: newComp } },
                    () => res.json(newComp)
                )
            );
        }
    );

Answer №1

It seems like you're looking to achieve this functionality through the code snippet provided below.

 router.post(
   "/projects/scenes/components/new",
   passport.authenticate("jwt", { session: false }),
   async (req, res) => {
     const newComp = new Components({
       content: req.body.content
     });

     await Project.findOneAndUpdate(
       { _id: req.body.projectID, "scenes._id": req.body.sceneID },
       {
        $push: { "scenes.$.components": newComp }
       }
     );

    res.json(newComp);
  }
);

Here's a similar issue that might help

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

Attempting to add text one letter at a time

Hey there! I'm new to JavaScript and Jquery, and I need some help. My goal is to display text letter by letter when a button is clicked using the setTimeout function. However, I seem to be encountering some issues. Any assistance would be greatly appr ...

What is the most effective way to extract information from a .txt file and showcase a random line of it using HTML?

As a newbie in HTML, my knowledge is limited to finding a solution in C#. I am attempting to extract each line from a .txt file so that I can randomly display them when a button is clicked. Instead of using a typical submit button, I plan to create a custo ...

Refreshing Three.js Scene to its Initial State

I am in the process of developing a Visual Editor where I can manipulate objects by adding, deleting, and transforming them. Currently, my scene only consists of a 5000x5000 plane as the floor. I am looking for a way to reset the scene back to its origin ...

Utilize webhooks for communication between a ReactJS user interface and a NodeJS server backend

I'm facing a situation where I have a ReactJS frontend and a NodeJS backend, and I need to integrate a 3rd party service that requires a URL to send HTTP POST requests with event data. However, due to the deployment settings of my app, only the fronte ...

In XML, it is not possible to click on images

It appears that the lightbox functionality is functioning properly at this time. However, there seems to be a strange straight line with an "x" and a round circle located at the top of the website, as if it's attempting to open something. You can vi ...

JSON Collaborator Tool

I really enjoy using the online json viewer at jsonviewer.stack.hu Does anyone know of a website that allows for sharing parsed json similar to sites like jsbin.com or jsfiddle.net ...

What could be causing the invalid_client error in response to this POST request I am making?

I am currently trying to establish a connection with an external API that has specific specifications: Host: name.of.host Content-Type: application/x-www-form-urlencoded Cache-Control: no-cache Through the utilization of the request module from npm, I am ...

Guide on how to reference the Html directory using the path module in Node Js

Desperately trying to send an html file as a response using express, but I'm having trouble locating the position or path of the index.html file. This is how my files are structured - MyWebsite Html index.html Css index.css ...

Performing AJAX in Rails4 to update boolean values remotely

Suppose I have a model named Post which includes a boolean attribute called active. How can I efficiently modify this attribute to either true or false directly from the list of posts in index.html.erb using link_to or button_to helper along with remote: ...

Sequencing numerous promises (managing callbacks)

I am encountering some challenges with promises when it comes to chaining multiple ones. I'm having difficulty distinguishing how to effectively utilize promises and their differences with callbacks. I've noticed that sometimes callbacks are trig ...

Re-sequence a contiguous array by mapping and filtering its elements

Within my React code, I have a list component that utilizes array.map to display a list of items. The list items have alternating backgrounds; every other item's background color is determined by whether the id field from the data structure is even o ...

Establishing the gulp-express configuration

I am in the process of developing an Express.js application and I am exploring options to include LiveReload capabilities for it. During my research, I came across a gulp plugin known as gulp-express. I attempted to configure my gulpfile.js following the ...

"Incorporating JSON and Ajax to dynamically populate one select based on the selection in another select

I need to display data from a JSON file in select options, and here is the structure of my JSON file: [{ "vehicle": "car1", "type": [ {"name" : "BMW", "details" : [{ "color" : "red", "price" : "50000" }, ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

Retrieve all fields in a MongoDB document

import pymongo client = pymongo.MongoClient(host='localhost', port=27017) db = client['db'] collection = db['foo'] data = [{ # doc 1 'foo': 'x', 'bar': 'y', ...

What is the reason for the absence of absolutely positioned elements in the render tree?

Recently, I came across some information about the render tree: As the DOM tree is being created, the browser simultaneously generates a separate tree known as the render tree. This tree consists of visual elements arranged in the order they will ap ...

Can you fill two dropdown menus with an array of choices?

I'm encountering an issue with using an array to populate two different select boxes. The first select box gets populated correctly, but when trying to add the same list to the second select box, it clears the first one and automatically selects the l ...

Utilizing jQuery and ajax to invoke an MVC controller

Hi there, I am currently facing an issue with calling a method in my controller using ajax and jquery with parameters Controller: [HttpPost("{Id}")] public ActionResult PostComment(int Id, ShowViewModel model) { } View: I have a button named AddCommen ...

"Which is the best practice for passing an ID parameter in a REST API - through the URL or in

After creating a web service with REST API, I have come across conflicting information in various tutorials. When passing a user id to the REST API, should it be included in the URL like this: 127.0.0.1:8080/users?userid=716360178 Or like this: 127.0.0 ...

After incorporating ng-view into my index file, I noticed that I was consistently encountering 404 errors when trying to load my templates

Solution Found! Issues in the App.js & Server.js files I am currently using Angular on the front-end with RouteProvider to deliver views to the client. I have set up routing, but when I insert ng-view into my index page, I encounter 404 errors for my vie ...