Creating a fresh entry into an array within a Mongo document using Meteor

Working on my first planning poker tool using Meteor, I am navigating through meteor and json document stores for the first time. For user stories, I have set up a Collection which includes the users assigned to each story and their ratings.

To start off, I will be doing some inserts like this:

Stories.insert({'story': stories[i], 'assignees': users, 'ratings': []});

...and an entry would resemble something along these lines:

{
  'story': 'some story',
  'assignees': ['Bob', 'Joe'],
  'ratings': []
}

Once a user has provided their rating for a particular story, it should be updated to display something like this:

{
  'story': 'some story',
  'assignees': ['Bob', 'Joe'],
  'ratings': [{'Bob': 2}, {'Joe': 5}] // Is there perhaps a better way to structure this?
}

I am struggling with writing the code to achieve this. Currently, what I have is:

var users = ['Bob', 'Joe'];
for (var i = 0; i < users.length; i++) {
  var user = users[i];
  var rating = {user: 1};
  Stories.update({}, {$push: {'ratings': rating}});
}

Regrettably, the outcome looks somewhat like this:

{
  'story': 'some story',
  'assignees': ['Bob', 'Joe'],
  'ratings': [{user: 1}]
}

Only one object in the ratings array, and the key is not even correct (it's just user instead of e.g., Bob). This issue might be related to JS hoisting and complexities in instantiating objects. Any feedback or advice would be greatly appreciated.

Answer №1

The issue at hand is utilizing a variable as a "key" for an object, which is not the correct approach. Instead, use bracket [] notation to dynamically assign the "key" like so:

var users = ['Bob', 'Joe'];
for (var i = 0; i < users.length; i++) {
  var user = users[i];
  var rating = {};
  rating[user] = 1;
  Stories.update({}, {$push: {'ratings': rating}});
}

A more efficient solution involves consolidating this process into a single update:

var users = ['Bob', 'Joe'];
var ratings = [];
for (var i = 0; i < users.length; i++) {
  var user = users[i];
  var rating = {};
  rating[user] = 1;
  ratings.push( rating);
}

Stories.update({}, {$push: {'ratings': { $each: ratings } }});

By using the $each modifier, you can push an array of new documents onto the existing array, reducing network updates.

If executing this operation from a browser client with minimongo, keep in mind that the second option may not be feasible. However, it is viable when performed from the server side.

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

What is the best way to write an SQL query to safely insert a record into a table with a dynamic name?

I'm working on a function that can insert a record into a table in PostgreSQL. The catch is that the table name needs to be a parameter for the function, and the column names are determined dynamically. To ensure protection against SQL Injection, I am ...

Can someone guide me on integrating Apache Superset as an application within a Django project?

What is the best way to integrate Apache Superset into my Django project as an app? I attempted to install Apache Superset using Docker, but now I am looking to fully incorporate the Superset tool into my Django project as one of the applications. ...

Function returns to execute another Function

Update: Is there a way to retrieve a value from a nested function and have it returned by the parent function? function returningFn() { function otherFn() { var value = 123; return value; //To be retrieved by returningFn } } I nee ...

Interaction between Jquery and local server

Having some trouble communicating with a local Java server using a jQuery post method. Here is the code I am using: $.post('localhost:5051/receive', {'plugs':client['plugins']}); where client['plugins'] contain ...

Delete specified fields from an object by making changes to the entire object

Stored within a mongoDB document is the following data: { _id: "123" order: 1 parent: "Dueqmd64nTxM3u9Cm" type: "article" unit: "kg" } Prior to updating the document, all saved data undergoes calculations and validation. Therefore, t ...

Stopping a build programmatically in Next.js involves implementing specific steps that aim to halt

Is there a method to programmatically halt the execution of npm run build in Next.js when a specific Error occurs within the getStaticProps function? Simply throwing an Error does not seem to stop the build process. ...

Bring in mongoengine into the project

I have a ListField(DictField) that contains items like - {'user_id': '12345', 'timestamp' : 'datetime-object'} In my mongoengine data structure, I am trying to figure out how to remove elements from the List based ...

The PHP query does not display any information when using JSON

I am fairly new to this, but I am attempting to tackle this issue. I find myself having to run similar queries on an SQL server multiple times. The problem arises when I invoke the PHP from HTML, as the getJson function or any other method does not return ...

Issue with localStorage.getItem preventing the navbar styling from being updated

Currently, I'm working on a website using Bootstrap and I am incorporating both light and dark themes. Everything seems to be functioning well except for one issue - when the page is refreshed, the browser doesn't retain the theme that was previo ...

Sharing pictures using filepond and vue 3

I am currently facing an issue while trying to upload an image using the filepond library. The problem I am encountering is that it returns a "419 error." As I construct my component in Vue, I have been experimenting with the following code: <file-pond ...

Is there a way to link multiple GET requests and combine their results into an array in JavaScript/Node?

The current code is a bit messy, and I'm still unsure about the then method. What each 'get' call returns: An array with some, but not all, results. What I need: To pass two different URIs, concatenate the results of both, and then expor ...

Filtering an array of objects by their attributes

How can I efficiently filter an array of objects by a specific value that could be located in any property? Consider the following object: var x = [ { name: "one", swp: "two" }, { name: "two", swp: "three" ...

Tips for comparing strings that are nearly identical

Looking to filter elements from an array based on partial matching of a string. For example, trying to match PGVF.NonSubmit.Action with NonSubmit by checking if the string contains certain keywords. The current code is not functioning as expected and only ...

Navigating with jQuery toggle paths

I am trying to create a path navigation system using jQuery. Below is the current code structure: $("#one_link").click(function() { $("#categories").css("display", "block"); $("#text_three").css("display", "none"); $("#cats_text").css("display", " ...

How can you delete a specific class name from a chosen element in VueJs?

My Vue.js method is set up like this. In the changeRoute function, I am able to change the class name by using e.target.className = 'clicked';. However, I am facing difficulty when trying to remove that class name from other elements using pre.re ...

Can the URL in angular.js be modified without having to invoke the controller

My current issue involves the following scenario: I am using the url http://localhost:8080/#/dashboard to display features in my dashboard. For instance, when the url changes to http://localhost:8080/#/dashboard/20, I need to load cities where the country ...

Adding a new field to an object residing within an array in MongoDB

I am working with an object called "user" that has the following structure: { "_id" : ObjectId("5edbdf57ac52325464b054ec"), ... "purchaseHistory" : [ { "_id" : ObjectId("5ee7a8f6b438a1254cec3f74"), ... }, ...

Avoid repeated rendering in Vue v-for loops

Here is the code I've captured: https://jsfiddle.net/prsauer/Lnhu2avp/71 The main issue at hand is that currently, every click on a list item triggers a call to computeStyle for each item. I would like it so that only one recompute of the style occur ...

Embed an array within a div using JavaScript

I'm looking to make a small adjustment to this code, acknowledging that it's far from perfect. Instead of simply writing the array contents into a single div, I'd like to create a new div for each number in the array and then add it to the c ...

"Enhancing User Interaction with jQuery Hover State Dropdown Menus

Here's my issue: I've created a drop-down menu and I want the text color to change when hovering over the menu. Additionally, I'd like the hover state to remain active when hovering over the submenu. Currently, I'm using this code: $( ...