我将此文档保存在名为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"
}
我正在尝试从此文档中选择数据并使用此代码将其保存到另一个文档中。目的是让上面文档中的examsubjects
值成为我插入的文档中的键。< / p>
'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
});
}
}
});
},
当代码运行时,保存主题值的变量subj
只是插入subj而不知道它是这样的变量
{
"_id" : "5yjwFanBAupgu9GHq",
"examschoolid" : "sms",
"examname" : "First",
"examsubjects" : [
{
"subj" : "0"
}
],
"examay" : "NrsP4srFGfkc5cJkz",
"examterm" : "5A5dNTgAkdRr5j53j",
"examclass" : "gYF2wE4wBCRy9a3ZC",
"examdate" : ISODate("2016-05-07T22:41:00Z")
}
为什么变量不被视为变量?。
修改
'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
},
更新的代码几乎可以使用,但只能插入1条记录。
答案 0 :(得分:2)
这就是JSON的工作原理,它从字面上理解了密钥。使用ES6括号表示法修复它:
examsubjects: [{
[subj] : "0"
}],
答案 1 :(得分:2)
这是因为它被视为文字对象中的一个键。
如果您希望将subj
的值作为键,则需要使用括号表示法,事先创建对象:
const subj = doc.examsubjects[i][prop];
let subject = {};
subject[subj] = "0";
Told.insert({
examschoolid:"sms",
examname:doc.examname,
examsubjects: [subject],
...
});