A guide on Updating a Collection of Subdocuments in a MongoDB Array using MeteorJS

I'm troubleshooting an issue with updating a mongo collection in my Meteor project.

It seems like I might be misunderstanding how $addtoset is supposed to function.

Below is the basic structure of my document, which is defined in my fixtures.js during project initialization:

var someUser = Meteor.users.findOne("W9YEs84QFhZzJeB6j");

var NewIdea = Ideas.insert({
  title: "This Is a Title",
  body: "Blah Blah Blah Body Goes Here",
  userId: someUser._id,
  author: someUser.profile.name,
  timestamp: new Date(now - 5 * 3600 * 1000),
  score: [],
  overallScore: 0,
  votedOnBy: [],
  timesVotedOn: 0
});

This is the desired updated version of the document:

{
  _id: "bKXXrpYmppFBfq9Kx",
  title: "This Is a Title",
  body: "Blah Blah Blah Body Goes Here",
  userId: "W9YEs84QFhZzJeB6j",
  author: "Users Name",
  timestamp: ISODate("2016-06-07T20:37:05.775Z"),
  score: [
    {
      userId: ""W9YEs84QFhZzJeB6j",
      score: 1
    }
  ],
  overallScore: 1,
  votedOnBy: [
    "W9YEs84QFhZzJeB6j"
  ],
  timesVotedOn: 1
}

This is the update code that I've attempted (without success):

Ideas.update("bKXXrpYmppFBfq9Kx", {
  $addToSet: {score: {userId: someUser._id, score: 1}},
  $inc: {overallScore: 1},
  $addToSet: {votedOnBy: someUser._id},
  $inc: {timesVotedOn: 1}
});

After executing this update, here's the resulting document displayed in the Mongo console:

{
  "_id" : "bKXXrpYmppFBfq9Kx",
  "title" : "This Is a Title",
  "body" : "Blah Blah Blah Body Goes Here",
  "userId" : "W9YEs84QFhZzJeB6j",
  "author" : "Users Name",
  "timestamp" : ISODate("2016-06-07T20:37:05.775Z"),
  "votedOnBy" : [
    "W9YEs84QFhZzJeB6j"
  ],
  "timesVotedOn" : 1
}

As observed, the fields overallScore and score are missing entirely.

Given my limited experience with Meteor and Mongo, I'm reaching out for guidance on what could be amiss with this update process. Any advice or insights are greatly appreciated!

Answer №1

One thing to keep in mind is that the modifier acts as an object. Consider the following example of an object literal:

{
  a: 1, b: 1,
  a: 2, b: 2
}

When evaluated, it results in:

{ a: 2, b: 2 }

This happens because the keys are reassigned multiple times, with the last assignment taking precedence.

In your implementation, the same principle applies to the $addToSet and $inc keys. To rectify this issue, structure your update as follows:

Ideas.update("bKXXrpYmppFBfq9Kx", {
  $addToSet: {
    score: { userId: someUser._id, score: 1 },
    votedOnBy: someUser._id
  },
  $inc: {
    overallScore: 1,
    timesVotedOn: 1
  }
});

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

Monitoring websites on a consistent basis and executing actions periodically

My idea is to post a question on a forum (like Stack Overflow) and have a program focus on it. The program would then send me an email when someone responds or answers my post. One approach I thought of is using PHP with file_get_contents or curl. Continu ...

What is the best way to save client IP addresses in an array using C for socket programming?

I'm working on a client/server program using sockets in C. I implemented inet_ntoa to retrieve the IP addresses of clients connected to the server. In my code, I have a loop that runs twice to connect two clients and store their IPs as integers in an ...

In Python, finding a solution to eliminate overlapping boundary ranges in lines

There is a file with the following content: 1 33725 36725 ENHANCER0002 1 711760 714760 ENHANCER0003 1 724150 727150 ENHANCER0004 1 725455 728455 ENHANCER0005 1 871280 874410 ENHANCER0006 1 874180 877180 ENHANCER0007 1 900540 90 ...

Tips for creating a validator function in Angular that only allows whole numbers between 0 and 30, excluding decimals

When a user enters a value between 0 and 30, the input should accept whole numbers like 0, 2, or 20 but not decimal values such as 20.1 or 0.1. I tried using validators min(0) and max(30), but they still allow decimal values. I need a validator that restr ...

Issue arising from the lack of direct communication between parent and child elements

I am facing an issue with indirect communication in a react native application. The situation involves a parent component, implemented as a class component, and a child component, which is a functional component. Here is the Parent component: constructor ...

How to Retrieve a Reference from a ListField in MongoEngine based on ID

I'm interested in removing certain references from a ListField(ReferenceField) based on their values alone. In my database, I have a Model that stores information about images: class ImageUrl(Document): src = UrlField() counter = IntField() ...

Transforming dynamic class based on state value from React to TypeScript

I'm trying to implement this React function in TypeScript, but I'm encountering errors. const ListItem = ({ text }) => { let [showMore, setShowMore] = useState(false); return ( <div className="item"> ...

The results from MongoDB have come back as an array filled with

I am facing an issue where I am trying to populate albums with images using the userid sent through params, but I am getting an empty array even though there is data in the database. "use strict" var express = require('express'); var app = expr ...

Clicking on the menu in mobile view will cause it to slide upward

I have implemented sticky.js on my website and it is working well. However, when I resize the browser to mobile view and click the main menu button, it goes up and I am unable to close it. I have to scroll up to see it again. How can I make it stick to the ...

Troubles with the mongoose population on the second tier

I have been encountering a server error while trying to populate multiple fields in a MongoDB using Mongoose. I am working with the latest versions of MongoDB, Mongoose, Node.js, and Express. My local MongoDB server is functioning properly. Here is the cod ...

Removing unwanted users in a React application

Recently, I started working with React. There's a project where I need to filter users based on their upvotes, with the user having the most upvotes appearing at the top. However, I'm struggling to implement this feature properly. Additionally, w ...

Using a combination of jQuery and JavaScript to switch image tags between different classes

I'm really struggling with this issue and could use some guidance. Essentially, I have a code that should change the class of an img tag when a user clicks on a div element. Let's take a look at the HTML structure: <li><img src ...

How can I insert a line break in a sorted list or array?

While using the sort method, I have been conducting experiments and unfortunately unable to find a solution. Can someone please provide some suggestions? The output always appears as an array. Is there a way to format it differently, such as having a new l ...

Unable to clear array within the ReactJS useEffect hook

I have a table view in React where I fetch an array from an API and display it. However, when the user enters something in the table search box, I'm attempting to clear the current state array and render the completely new result. Despite my efforts, ...

Suggestions for structuring a MongoDB database for a to-do list application

In the process of developing a project management application that includes 'jobs' and 'entities' (or tasks) within those jobs, I am currently designing a unique todo list for each user and looking for the best database design approach. ...

Having trouble finding the file '../node_modules/bootstrap/dist/css/bootstrap.min.css'?

I'm currently working on a project where I am using react-bootstrap-table2 to create a bootstrap table. However, I encountered the following error: Failed to Compile: Module not found: Can't resolve '../node_modules/bootstrap/dist/css/boo ...

Is there a way to speed up MongoDB imports by running them concurrently using Airflow?

Summary: We are facing limitations on the speed of data insertion into our mongodb atlas cluster. Despite trying to insert data in parallel, we have not seen an increase in speed. How can we improve this process? Do we need to upgrade to a larger mongodb a ...

Dynamically load current components in Angular 2's final release

In my quest to dynamically load a component in the upcoming release version 2.0.0, I encountered some challenges. Previously, in RC5, I utilized the following code for loading: I created a directive responsible for loading the controls: import { Check ...

After the animation has finished, the ".animated" class should be removed. If the element is reloaded, the class should be added back using plain

Within my CSS, there is a ".animated" class that is automatically applied to all elements with the "drawer-wrapper" class. The HTML structure looks like this: <div class="drawer-wrapper animated"> foo </div> I created a function that ...

What causes the text field and checkbox to move downward as I enter text?

I'm currently working on a mock login page using React and Material UI. I implemented a feature where the show/hide password icon only appears when the user starts typing in the password field. However, after making this change, I noticed that the pas ...