我的目标是使用包含“用户名”属性和“评级”值的对象来更新集合文档。该对象将被推送到文档中已存在的“评级”数组。
无论出于何种原因,属性“username”都被视为字符串而不是其变量值。 “评级”值被正确抓取和推送。
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: {
// When pushing to ratings array, the {username: rating} object treats 'username' as a string instead of a variable.
ratings: {username: rating}
}
}
);
}
});
我很困惑,因为控制台日志中途确实记录了正确的用户名。
无论如何,无论发生什么,集合文档上的“评级”数组看起来都是这样的:
[{username: 3}, {username: 5}, {username: 2}, {username: 4}]
而不是这样的:
[{joesmith: 3}, {janedoe: 5}, {kevincostner: 2}, {donaldtrump: 4}]
最佳答案
对于 JavaScript 对象,您无法使用文字对象表示法来正确命名变量。您必须使用数组表示法。
因此,对于您的示例,您可以这样写:
var obj = {};
obj[username] = rating;
Puns.update({ _id: currentPun._id}, {
$push: {
ratings: obj
}
});
关于javascript - MongoDB(通过 Meteor)在更新集合文档时将对象属性视为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34868297/