Locate and modify a value within an object in a nested array using Meteor collection

I'm currently facing a challenge in figuring out how to locate a specific document within a collection, and then pinpoint a value within an object nestled in a subarray of that document — subsequently altering a value within that object.

My objectives are as follows:

  • Locate by _id

  • Identify the object in the ratings array that corresponds to the user + post keys

  • Modify the report value within that object

To provide context, the structure of the documents in my collection is outlined below.

{
    "_id" : "mz32AcxhgBLoviRWs",
    "ratings" : [
        {
            "user" : "mz32AcxhgBLoviRWs",
            "post" : "SMbR6s6SaSfsFn5Bv",
            "postTitle" : "fdsfasdf",
            "date" : "2017-09-27",
            "rating" : "4",
            "review" : "sdfa",
            "report" : "a report"
        },
        {
            "user" : "mz32AcxhgBLoviRWs",
            "post" : "iZbjMCFR3cDNMo57W",
            "postTitle" : "today",
            "date" : "2017-09-27",
            "rating" : "4",
            "review" : "sdfa",
            "report" : "some report"
        }
    ]
}

Answer №1

Looking to consolidate your updates into one query instead of three separate ones?

Collection.update({
  _id: <id>,
  ratings: {
    $elemMatch: {
      user: <user>,
      post: <post>
    }
  }
}, {
  $set: {
    'ratings.$.report': <report>
  }
});

For more information, check out the MongoDB documentation on $elemMatch and <array>.$.

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

"Here's a cool trick: A guide on dynamically inserting a value into {% url tag %} using JavaScript within

Incorporating leaflet JS into a Django template, the aim is to display markers on a map where latitude and longitude are sourced from a queryset. Sending the queryset through views and utilizing the Django template language within <script> tags seeme ...

Issue with JavaScript's variable scoping

After testing my application, I found that the following code was originally working: var htm = "<div> My content </div>"; $("#divprint").html(htm); window.setTimeout('window.print()', 4000); However, when I attempted to enclose it ...

The error message states: `discord.js TypeError: Unable to access the property 'resolve' as it is undefined`

Encountering an issue with the following code snippet const Discord = require('discord.js'); module.exports = { name: 'info', description: "Shows BOT's Informations", execute(message, client, args) { c ...

Having more than one bootstrap modal on a single page is not supported

I'm stuck and can't figure it out. I have multiple triggers that are very similar <a style="margin: 4px 4px 4px 4px !important" data-toggle="modal" data-target="#video_modal" data-title="YouTube v ...

Combining various collections using Mongoose in your application

I am currently developing a basic chat service using mongoose and nodejs. In my project, I have created two models - one for storing messages and another for tracking read information: var ChatModel = new Schema({ to: String, from: String, me ...

What steps do I need to take to integrate Twilio's SMS service into an HTML document?

I have been searching for solutions using php and node.js (which is a derivative of js, so it should work), but I came across this library: <script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.4/twilio.min.js"></script> ...

Is it possible for me to rearrange the sequence of Apple, Banana, Mango, Pineapple, and Kiwi?

arrange() organizes the elements in a custom order: var fruits = new Array("Apple", "Banana", "Kiwi", "Ananas", "Mango"); Namen.arrange(); document.write(fruits); I don't want them alphabetically sort ...

What is the best way to create a circular to square gradient and save it within a two-dimensional array?

Can anyone guide me on creating a circle/square gradient and storing the data in a 2D array? I want to incorporate this gradient with simplex-noise to develop a procedural island by subtracting the gradient from the generated noise. Here are some visual re ...

What steps do I need to take in order to make fullscreen slides?

Seeking assistance in developing full-screen slides similar to those found on the following website... The browser scrollbar should be hidden, and the slides should automatically transition when scrolling up/down or using the up/down arrow keys, with the a ...

Error Not Captured: [$rootScope:infdig]

Here is a code snippet that I wrote: <tbody ng-repeat="dtataOne in dataOnes()"> <tr> <td>My Data</td> <td class="task-container ui-sortable" colspan="6" ng-model="dtataOne.MyModel" ui-sortable="sortableOption ...

Nested Redux action creators call one another

Utilizing ducks alongside Redux, I have multiple action creators within the same file. I am seeking a way to call one action creator from another without the need for double dispatching in every case within the switch statement below: ... export function ...

Creating dynamic animations by shifting the hue of an image on a canvas

Recently, I've been exploring the world of canvas tags and experimenting with drawing images on them. My current project involves creating a fake night/day animation that repeats continuously. After trying various approaches like SVG and CSS3 filters ...

Disable the click functionality while preserving the hover feature

Due to my previous question being incorrectly marked as a duplicate, even though it wasn't, and no one is rectifying the mistake, I am re-posting my inquiry. I am dealing with an <a> element that has a default onClick function. This <a> a ...

Learn how to import a stylus file globally in Vite build tool

Recently, I decided to use vite for building a new vue application. However, I encountered some difficulties when trying to globally import a stylus file in my vite.config.js. I followed the code examples provided in the vite documentation: export default ...

There appears to be an issue with 'session' being undefined in this JS/Express/Redis setup for session storage

I've been experimenting with using redis for sessions in my express app. This is what I'm doing: server/auth.js import express from 'express'; import uuid from 'uuid'; const router = express.Router(); router.route(' ...

What is the best way to implement the node.js function into a typical frontend JavaScript file?

I created a node.js puppeteer script to extract data on covid cases in Canada. Now, I want to integrate this function into a frontend website built with JavaScript to display information on Canada's covid cases. How can I export this function to a Jav ...

What are some strategies for debugging a live Angular2/Typescript application?

As I start the exciting journey of creating a new app with Angular2 and Typescript, two technologies that I have never used together before (although I do have experience using them individually), a question arises in my mind. How can I effectively debug ...

AngularJS encounters an error with ng-model when a string is entered as the input type for a

What happens when the value of ng-model is a "24" (string) instead of 24 (number) on an input[type="number"]? It triggers the following error: Error: [ngModel:numfmt] http://errors.angularjs.org/1.5.8/ngModel/numfmt?p0=24 I attempted to set the input l ...

The ready/load frame event fails to trigger when a new frame URL is loaded

I currently have a website that uses frames, allowing users to change the content of a frame with a simple link that loads the new page in that frame. My goal is to determine when this loading process is complete. $(top.frames['mainFrame'][&a ...

"Present a continuous sequence of images in HTML to create a dynamic video-like experience

A PHP file has been created to extract images from a MySQL database and display them as a sequence of images that update every half second. Using the setInterval method in JavaScript, the page is refreshed every half second to display a new picture. $(doc ...