Adding a nested data structure in a Meteor application

In my mongo collection, I have a document named exam.

// meteor:PRIMARY> db.exam.find()
{
    "_id" : "RLvWTcsrbRXJeTqdB",
    "examschoolid" : "5FF2JRddZdtTHuwkx",
    "examsubjects" : [
        {
            "subject" : "Z4eLrwGwqG4pw4HKX"
        },
        {
            "subject" : "fFcWby8ArpboizcT9"
        }
    ],
    "examay" : "NrsP4srFGfkc5cJkz",
    "examterm" : "5A5dNTgAkdRr5j53j",
    "examclass" : "gYF2wE4wBCRy9a3ZC",
    "examname" : "First",
    "examdate" : ISODate("2016-05-07T22:41:00Z"),
    "examresultsstatus" : "notreleased"
}

I am attempting to extract data from this document and store it in another document using the following code. The goal is to use the value of examsubjects from the previous document as the key in the new document.

'click .reactive-table tr': function() {
    Session.set('selectedPersonId', this._id);
    var cursor = Exam.find({ _id:
            Session.get("selectedPersonId")}).fetch();
    cursor.forEach(function(doc){
        for (i = 0; i < doc.examsubjects.length; i++) {
            for (var prop in doc.examsubjects[i]) {
                console.log("obj." + prop + " = " + doc.examsubjects[i][prop]);
                var subj = doc.examsubjects[i][prop];
                Told.insert({
                    examschoolid:"sms",
                    examname:doc.examname,
                    examsubjects: [{subj : "0"}],
                    examay:doc.examay,
                    examterm:doc.examterm,
                    examclass:doc.examclass,
                    examdate:doc.examdate
                });
            }
        }
    });
},

However, when the code runs, the variable subj, which holds the subjects value, only inserts "subj" instead of recognizing it as a variable.

{
    "_id" : "5yjwFanBAupgu9GHq",
    "examschoolid" : "sms",
    "examname" : "First",
    "examsubjects" : [
        {
            "subj" : "0"
        }
    ],
    "examay" : "NrsP4srFGfkc5cJkz",
    "examterm" : "5A5dNTgAkdRr5j53j",
    "examclass" : "gYF2wE4wBCRy9a3ZC",
    "examdate" : ISODate("2016-05-07T22:41:00Z")
}

Why is the variable not being interpreted as a variable?

Edit

'click .reactive-table tr': function() {
    Session.set('selectedPersonId', this._id);
    var cursor = Exam.find({ _id: Session.get("selectedPersonId")}).fetch();
    cursor.forEach(function(doc){

        var sq = function(){
            for (i = 0; i < doc.examsubjects.length; i++) {
                for (var prop in doc.examsubjects[i]) {
                    const subj = doc.examsubjects[i][prop];
                    let subject = {};
                    subject[subj] = "0";
                    return [subject];

                }
            }
        }
        console.log(sq());
        Told.insert({
            examschoolid:"sms",
            examname:doc.examname,
            examsubjects: sq(),
            examay:doc.examay,
            examterm:doc.examterm,
            examclass:doc.examclass,
            examdate:doc.examdate
        });

    });
    //Uncaught TypeError: cursor.count is not a function
},

The updated code almost works, but it only inserts one record.

Answer №1

This is the method JSON operates, it interprets keys verbatim. To correct this, implement ES6 bracket notation:

examSubjects: [{
  [subject] : "0"
}],

Answer №2

The reason for this behavior is that it is considered a primary key in an object literal.

If you wish to use the value of subj as your key, you will have to employ bracket notation and create the object beforehand:

const subj = doc.examsubjects[i][prop];
let subject = {};
subject[subj] = "0";

Data.insert({
    schoolid:"abc",
    examname:doc.examname,
    examsubjects: [subject],
    ...
});

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

Storing user input from Vue.js in a JavaScript array for future use

Utilizing vue.js <template> <input id="email" v-model="email" type="text" placeholder="Email"> <input id="name" v-model="name" type="text" placeholder=" ...

Exploring jQuery AJAX Attributes during ajaxStart and ajaxStop event handlers

With my project consisting of over 40 ajax webservice calls, I am looking to incorporate additional debugging features. One such feature is a timing method which I have already developed using my Timer class/object in Javascript. I'm seeking assistan ...

How can you use mouseover events to display a popover and manipulate the div id?

In my scenario, I have multiple div elements and I want to display separate popover for each div. Initially, the popover is not shown on the first mouseover event but works perfectly on subsequent attempts. Below is the code snippet: $(document).read ...

Can you outline the key distinctions between AngularJS and ReactJS?

Looking to create a website that will be converted into a mobile application, I realize that my expertise lies more in desktop and Android native development rather than web client side development. After some research, I have decided to utilize HTML5, CSS ...

Struggling with certain aspects while learning Nodejs and ES6 technologies

Below is an example of using the ES6 method.call() method that is causing an error var obj = { name: "Hello ES6 call", greet: function(somedata) { this.somedata = somedata console.log(this.somedata) ...

A handy feature of HTML5 is the dataset attribute, which

Is there a way to restrict the height of the dataset dropdown list in HTML? When using <input list="datalist"> with numerous elements, some might not be visible. Is it possible to limit the size of the list and enable vertical scrolling to display al ...

React SVG not displaying on page

I am facing an issue with displaying an SVG in my React application. Below is the code snippet: <svg className="svg-arrow"> <use xlinkHref="#svg-arrow" /> </svg> //styling .user-quickview .svg-arrow { fill: #fff; position: ...

Organizing a Vue.js SPA project: Implementing Vuex store and API calls efficiently

Here is how I have organized the structure of my Vue app: components/ article/ AppList.vue common/ AppObserver.vue NoSSR.vue layout/ AppFooter.vue AppHeader.vue ui/ AppButton. ...

What is an alternative way to retrieve the page title when the document.title is unavailable?

Is there a way to retrieve the page title when document.title is not available? The code below seems to be the alternative: <title ng-bind="page.title()" class="ng-binding"></title> How can I use JavaScript to obtain the page title? ...

What is the best way to reset a setInterval ID in Angular?

In my Angular project, I am developing a simple timer functionality that consists of two buttons – one button to start the timer and another to stop it. The timer uses setInterval with a delay of 1000ms. However, when the stop button is pressed, the time ...

Utilizing mongoose to reference a sub-field

Is it possible to populate myBook.title by referencing the sub field/id of subject.book._id? let subject= new Schema({ subjectTitle{ first:String, last: String, }, book[ { title: {type: String, requ ...

The NEXT_LOCALE cookie seems to be getting overlooked. Is there a mistake on my end?

I am looking to manually set the user's locale and access it in getStaticProps for a multilingual static site. I have 2 queries: Can a multilingual website be created without including language in the subpath or domain? Why is Next misinterpreting m ...

Error in Next.js: .env variable not defined

I recently transitioned my project from React to Next.js and encountered an issue where my environment variables are showing as undefined, even though they were functioning correctly in React. Can someone provide some guidance or assistance with this probl ...

What is the best way to display a <div> depending on the screen size in React JS using a global variable, without utilizing state management?

I am attempting to display a message based on the screen resolution in ReactJS. I am utilizing a function component and trying to accomplish this without using state, by using a global variable. const isDesktop = window.innerWidth; {isDesktop > 768 ? ...

Adjust the styling with jQuery according to the selected value from the dropdown menu

Check out this Fiddle I have a jQuery script that is supposed to change the style of an input box to display:block if the selected value is "<>" (Between). However, currently it is changing the css for all selected items instead of just the target i ...

Encountering an unexpected token error while building an Angular4 --prod project that involves Three

Encountering an error while trying to build an Angular4 project in production with the following command: node --max_old_space_size=8192 'node_modules/@angular/cli/bin/ng' build --prod --output-hashing=al Error: ERROR in vendor.422622daea37e ...

Show the React component upon clicking the Add button

I recently developed a React component that reveals a new section whenever the user clicks the "New Section" button. However, I have encountered an issue - I would like the component to display multiple sections based on how many times the button is clic ...

What is the reason for this JavaScript code not activating the input field (aspx)?

Thank you for taking the time to review this. I understand that for most of you client side scripting experts, this task is a breeze. However, all I am trying to achieve is to display a message at the top notifying the user that their click has been regist ...

Remove an owl carousel using Laravel, Vue.js, and Axios

I've implemented a sleek slider on my website to showcase images with accompanying text to visitors. The slider utilizes owl carousel within a vue component and is functioning properly. Now, I'm attempting to add a delete button so that users who ...

ERROR: Unexpected issue occurred with v8::Object::SetInternalField() resulting in an internal field going out of bounds while utilizing node-cache in Node.js

I recently started working with API exports that contain a large amount of data, so I decided to utilize the node-cache in order to speed up the API response time, as it was taking more than 2 minutes to retrieve the data. Being new to this, I came across ...