Inserting a nested object in mongo


#1

I have this document saved in my mongo collection called 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 trying to select data from this document and saving it into another using this code.The aim is to have the examsubjects value in the document above to be the key in the document i am inserting into.

					 '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];
         const subj = doc.examsubjects[i][prop];
let subject = {};
subject[subj] = "0";
        Told.insert({
	    examschoolid:"sms",
	    examname:doc.examname,
	    examsubjects: [subject],
	    examay:doc.examay,
	    examterm:doc.examterm,
	    examclass:doc.examclass,
	    examdate:doc.examdate
            });
         }
        }
           // console.log(doc.examsubjects);
          });   
            //Uncaught TypeError: cursor.count is not a function
             },

Instead of creating two subjects under exam projects,my code inserts two separate records with the two subjects.

How can i go about inserting the two subjects under examprojects?.


#2

I moved the looping code to the nested field

  Told.insert({
        examschoolid:"sms",
        examname:doc.examname,
        examsubjects: function(){
             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];
         const subj = doc.examsubjects[i][prop];
		 let subject = {};
		 subject[subj] = "0";
      return [subject];
         }
        }  
        },
        examay:doc.examay,
        examterm:doc.examterm,
        examclass:doc.examclass,
        examdate:doc.examdate
            });

but examsubjects objects are not inserted