How to add a group of items to a nested document using an index?

I've been working on the code below to create a new subdocument within an existing subdocument. The structure is as follows:

User -> (Many Comments) -> (Many Ratings).

The rating object is a simple JavaScript object with the format;

rating: {
    userId: "userId",
    rating: 4
}

For the comment at index [0], I'm trying to add a new rating using the following code;

db.getCollection('Users').update(
                {id: "user123", },
                {
                    $push: {
                        comments[0].ratings: rating
                    }
                })

When I ran this in the mongo console, with a test string for the rating value, I received the error message;

Error: Line 5: Unexpected token [

To overcome this, I tried enclosing commas around comments[0];

db.getCollection('Insights').update(
                    {id: "b5e5bf69-071b-4af2-99b2-5165b47499cb", },
                    {
                        $push: {
                            "comments[0].ratings": "test"
                        }
                    })

This update was successful;

Updated 1 existing record(s) in 2ms

However, the subdocument does not appear as expected.

If someone could guide me in the right direction, I would greatly appreciate it.

Answer №1

I discovered a solution to this issue; the array[index] structure is not compatible with Mongo. It is recommended to utilize object notation instead. Therefore, replace;

$push: {"comments[0].ratings": "test"}

with;

$push: {"comments.0.ratings": "test"}

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

Is there a way to consolidate all Vue.js routes, templates, and components into a single file?

I am currently working on a Vue.js example where I aim to consolidate everything into a single file. My goal is to demonstrate the efficiency of using a small silo that can serve multiple routes. Here is what I have accomplished so far: <html> <h ...

How to redirect to a different view or controller using ASP.NET and AngularJS

How can I open the View located at /Home/CreateItem after clicking on the Add button? What do I need to include in my code? $scope.Add = function() { console.log('working'); } This is how Index.cshtml looks like: <script src="~/ ...

Accessing the window variable within a Jquery selector in Javascript

I'm encountering some issues while attempting to optimize code. The following lines execute without errors: Array.prototype.forEach.call( $('ZA1 .stat'), function( td ) {//ExcuteCode} Array.prototype.forEach.call( $('ZA2 .stat'), ...

Unable to modify existing attributes in a sails.js model

I'm new to sails.js and I have a question about adding fields to an existing model in Sails.js. Here is the current model: module.exports = { attributes: { id: { columnName: 'id', type: 'integer&apos ...

Explore the HTML elements in order to determine their respective position

In the midst of working on a chat app project, I've managed to create a code that aligns the chat bubbles to the left for users other than myself, and to the right for my own messages. While the code does function as intended for the first chat bubbl ...

Automatically Parse Value by 100 in Angular FormGroup

Within my Angular form group, I have 3 fields. One of these fields serves as a tool for the user, automatically calculating the value based on another field. Essentially, when a user inputs a number, the tool field displays that value divided by 100. Here ...

React setState not triggering to close Material-UI dialog

I have implemented my own Material UI dialog component, separate from the provided demos at https://material-ui.com/demos/dialogs/ When I open the dialog, the state changes from false to true. I have included a handleClose function to close the dialog and ...

Using Javascript to Discover and Add Elements to an Array

I am facing a challenge with a dataset retrieved from an AJAX call, which contains a list of users and their roles in connection to the project. Some users can have multiple roles, leading to their presence in the result set in different instances. I am ...

Refresh your webpage with new content and modified URLs without the need to reload using window.history.pushState

Hey everyone, I'm looking to incorporate window.history.pushState into my website, but I'm unsure of how to go about it... What I'm aiming for is to have a page dashboard.php and update the URL to dashboard.php?do=edit&who=me, while loa ...

loop failing to refresh element within array

Is there a way to update a specific property in every element of an array to match its index? I attempted the following approach: static reindexComponentsOnMultiplePages(components) { return components.forEach((el, idx) => (el.componentIndex = id ...

The Angular 2 view will remain unchanged until the user interacts with a different input box

I am currently working on implementing form validation using Reactive Forms in Angular 2. Here is the scenario: There are two input fields Here are image examples for step 1 and step 2: https://i.stack.imgur.com/nZlkk.png https://i.stack.imgur.com/jNIFj ...

JavaScript: void(0), Internet Explorer 6, and SWFAddress are all important components

Hello there, We are on the verge of launching a secure website (regrettably, we cannot provide the URL) and have come across a rather obscure bug in IE6 that I am hoping someone may have experienced or could shed some light on. This issue only arises when ...

Adjust the height of Fullcalendar when the window is resized to maintain the aspect ratio as it shrinks

I am having trouble adjusting the height of an FC (fullcalendar) within a div. My goal is to have the FC completely fill the div without overflowing. Despite setting the height attribute during initialization, the FC's height does not resize properly, ...

Tips for handling Google Spanner Date type in JavaScript

I am facing a challenge with Google Cloud Spanner as I work with multiple tables containing columns of type Date. While inserting entries with specified dates works fine, the issue arises when trying to retrieve these entries in the JavaScript frontend. Th ...

When the caret triangle is upside down, it indicates that a drop-down menu is available even when the

I am facing an issue with a dropdown list where the triangle indicator is incorrectly displayed: https://i.stack.imgur.com/L4NBW.png Both images show that the arrows are in reverse direction, and I am struggling to identify the cause of this problem. He ...

Is there a way to convert JSON objects for transmission between Google Appscript and its HTML interface?

Google Appscript has the capability to transfer data from server-side scripting to client-side HTML. E.g. appscript.gs var htmlServ = HtmlService.createTemplateFromFile("addDetailsBookingForm"); let order_id = getSheetOrderID(sheet); //let ...

Creating interactive ng-models for form controls using AngularJS

I am working on a project where I have an Array in my controller. This Array is being used to dynamically generate input fields on the page. Here is a snippet of my AngularJs code: var app = angular.module('plunker', []); app.controller(' ...

What is the best way to attach a single block of Javascript code to different div elements without executing them simultaneously?

Running a small ecommerce shop, I have designed product cards using HTML, CSS, and a bit of Jquery for animations. However, a problem arises when clicking the "add to cart" button on any product card as it adds all items to the cart and triggers animations ...

Storing tweets in a mongodb database using nodejs

I have successfully written a code using nodejs to fetch data from twitter. Now, I am facing difficulty in storing it in mongodb. Can someone please provide me with step-by-step guidance on how to achieve this? I am unable to do it on my own. var app = ...

Issue with Next-Auth getServerSession failing to fetch user data in Nextjs 13.4 API Route

Having an issue with accessing user session data in a Next-Auth/Nextjs 13.4 API Route. I've set up the JWT and Session callback, but the user data defined in the callback function isn't translating correctly to what getServerSession is fetching i ...