When using MongoDB with Meteor, object properties are automatically converted to strings when updating a collection document

I am currently working on updating a collection document by adding an object that includes a 'username' property along with a 'rating' value. This particular object is supposed to be pushed into the existing 'ratings' array within the document.

Strangely, the 'username' property seems to be interpreted as a string rather than its expected variable value. On the other hand, the 'rating' value is correctly retrieved and added to the array.

Template.Rating.events({
  'submit form': function (event, template) {
    event.preventDefault();

    var form = template.find('form');
    var rating = template.find('input[name="rating"]:checked').value;
    var currentPun = Session.get('randomPun');
    var username = Meteor.user().username || null;

    console.log(username);
    Puns.update(
      { _id: currentPun._id},
      {
        $push: {
          // The issue arises when pushing to the ratings array; the {username: rating} object interprets 'username' as string instead of a variable.
          ratings: {username: rating}
        }
      }
    );
  }
});

I find it perplexing that the correct username is displayed in the console log halfway through the code.

Due to this discrepancy, the 'ratings' array within the collection document appears like this:

[{username: 3}, {username: 5}, {username: 2}, {username: 4}]

Instead of appearing as intended:

[{joesmith: 3}, {janedoe: 5}, {kevincostner: 2}, {donaldtrump: 4}]

Answer №1

When working with JavaScript objects, it is not possible to correctly name a variable using literal object notation. You must instead use the array notation.

For your specific example, the code would look like this:

var obj = {};

obj[username] = rating;

 Puns.update({ _id: currentPun._id}, {
    $push: {
      ratings: obj
    }
 });

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

Issues with undefined elements in Vue.js arrays---Need any more help with reph

I'm encountering some issues with my Vue.JS code. I'm trying to access the 5th element of my array, and it's working fine, but Vue is also throwing a couple of errors. Here's the code I'm using to retrieve my data: <div> ...

AngularJS does not run the code inside the ref once directive

Code within the block of this.verifyUserToken does not execute. It appears that the issue may stem from asynchronous calls, as the data returned is not yet available. I am unsure of how to proceed in handling this. this.verifyUserToken = function(){ ...

Unfulfilled Peer Dependency in react

Encountering javascript issues with react. Chrome error message when rendering page: Uncaught TypeError: Super expression must either be null or a function, not undefined at _inherits (application.js:16301) at application.js:16310 at Object.232.prop-types ...

Using window.open and appending a new feature to it

Below is the code found in my index.html file: <!DOCTYPE html> <html> <head> <script> function createDialogBox() { var dialogBox = window.open("in1.html"); dialogBox.nameBox= "my little box" } window.onload = createDialogBox; wind ...

Using ASP.NET MVC 6 Web API along with Angular, a resource can be posted as an object property in the

I am facing a challenge in sending a complex object from Angular to my web API. Here is how the object looks: { Name: "test", Tax: 23, Addresses: [ { country: "ro", city: "bucharest" }, { country: "fr", ...

Running 'npm test' is successful, however the 'jest --coverage' command fails to execute

In my MonoRepo project (using Lerna), I have multiple packages, with one being a React application. For unit testing in the React project package, I rely on Jest. However, when I try to execute the jest --coverage command in the WebStorm console, it shows ...

Issue with Ref when used in a distinct HTML template

I have encountered a frustrating issue with my simple Vue project. When I separate the template and code into individual files, the ref stops working and I end up with an undefined value in the HTML template. This scenario works fine: map.component.vue ...

Need to transfer a variable from the left side to the right side within Javascript. The instructor demonstrated using up and down as an

Recently started learning JavaScript as part of my college game programming course. I am only using Notepad for coding. Currently, I am trying to move an object (in this case, just the letter "o") from left to right on the screen. My professor has provided ...

Leverage the power of the YouTube API to determine if a video is able to be embedded

As I delve into the YouTube Data API v3 to determine if a particular video is embeddable, I have come across the status.embeddable property that seems crucial. By making a request like this: https://www.googleapis.com/youtube/v3/videos?id=63flkf3S1bE& ...

Top method for creating a checkbox filter to toggle the display of elements depending on various data-* attributes

I am currently working on creating a checkbox filter that will display or hide elements based on multiple data attributes assigned to those elements. Despite my attempts, I have not been able to achieve the desired filtering outcome. You can view a basic ...

Error encountered while executing jest tests due to an unexpected import token

Despite trying numerous solutions and suggestions on Stack Overflow, I am still unable to resolve the issue at hand. I recently discovered jest and attempted to use it by following a tutorial on testing React components with jest from DZone. However, when ...

How to Add to a Nested Array in Mongoose based on a Condition

Consider the schema below: { userId: docId, skills: [ { _id: SkillId, endorsers: [ { userId: idOfUser } ] } ] } I am trying to ensure that a user cannot endorse a specific skill in a document mult ...

The fade-in effect will initiate from the start once the mouse leaves the element (with a

Currently, I am in search of a solution for improving the navigation menu I am developing. By clicking on this JSFiddle link, you can view the code in action. The issue I am facing is that the fadeIn effect should only occur when hovering over the nav-ite ...

Ways to showcase Switch/Case in two separate drop-down menus

I'm currently working on a PHP file with a switch/case structure that I believe is in JSON format. While I may not be an expert in PHP, AJAX, and JSON, I'm really putting effort to learn more about it. <?php switch($_GET['make'] ...

Is there a recursive method to verify the folder name for each aggregate?

Consider the scenario with these sample documents: (parent_id: null denotes items located at root directory) {"_id":"a", "name":"Pictures", "parent_id": null, "type": "folder"} {"_ ...

Remove dates from MongoDB to prepare for presentation on the front end

After importing dates into Mongo, they save as Dates and include UTC time information. When extracting these dates from Node, how can I format them properly? Current result: Thu Jan 20 2011 00:00:00 GMT-0700 (MST) I would like to remove everything a ...

What are some strategies for improving search efficiency in arrays containing over 50,000 elements?

I am working with a large array of strings containing about 50,000 elements. export const companies = [ "000014", "000016", "000017", "000019", "000020", "000021", "000023" ...

Is there a way to confirm if all div elements have a designated background color?

I have a scenario where I have dynamically added several divs with a specific class to my webpage. These divs change color when the user hovers over them. I am trying to trigger a specific function once the last div has been set to a particular backgroun ...

Utilizing Node as an intermediary to transmit form-data to a Java server

I am working on an application that utilizes axios for communication with a node server, which then interacts with a separate java server. Calling the node server from the client: // assuming payload is of type FormData() axios.post(url, payload).then((r ...

Mongoose managing diverse connections

Currently, I am working with Node.Js 8.6 and Mongoose 4.11, managing multiple database connections using mongoose.createConnection. Upon exploring the connections property within the mongoose object (an array that stores established connections), I am curi ...