【发布时间】:2015-01-17 06:41:34
【问题描述】:
几天来,我一直试图弄清楚如何让 forEach 循环在 Meteor 中工作。我有一个 QuestionList 集合,其中包含两个数组 (usersTrue usersFalse) 供猜测问题的人使用。当我回答问题时,我想通过这两个数组并更改用户分数。我想我真的很接近,但我错误地调用了两个集合之一。
两个集合QuestionList 链接到问题集合和UserList 连接到Meteor.users
我有出版物
Meteor.publish('activeQuestions', function(){
return QuestionList.find({ });
});
Meteor.publish('userNotAnswered', function(){
var currentUserId = this.userId;
return QuestionList.find({active: true, usersTrue: {$nin: [currentUser]},
usersFalse: {$nin: [currentUser]}});
});
Meteor.publish('userAnswer', function(){
var currentUserId = this.userId;
return UserList.find({_id: currentUserId});
});
当我回答问题时,我有管理方面的模板。它使用几个参数调用modifyQuestionStatus 方法。
Template.activeQuestionList.events({
'click [data-action=questionTrue]': function() {
// Select the id of the yes button that is clicked
var questionId = this._id;
Session.set('answered', questionId);
// Get the session
var answered = Session.get('answered');
// Update the database without losing any data
Meteor.call('modifyQuestionStatus', answered, true);
},
'click [data-action=questionTrue]': function() {
// Select the id of the yes button that is clicked
var questionId = this._id;
Session.set('answered', questionId);
// Get the session
var answered = Session.get('answered');
// Update the database without losing any data
Meteor.call('modifyQuestionStatus', answered, false);
}
});
终于有了方法
'modifyQuestionStatus' : function(questionId, answer){
QuestionList.update(questionId, {$set: {active: false, answer: answer}});
var base = QuestionList.find({_id: questionId});
if (answer === true) {
base.usersTrue.forEach(function (user) {
user.update(secret, {$set: {coins: 100}} );
});
base.usersFalse.forEach(function (user) {
user.update(secret, {$set: {coins: -100}} );
});
} else {
usersFalse.forEach(function (user) {
UserList.update(secret, {$set: {coins: 100}} );
});
usersTrue.forEach(function (user) {
UserList.update(secret, {$set: {coins: -100}} );
});
}
},
secret 是存储硬币的数组。
我知道代码并不完美,但我想在清理之前让代码正常工作。我想我提供了足够的信息。我是编程新手,所以如果我遗漏任何有助于回答问题的内容,请告诉我。
【问题讨论】:
-
你遇到了什么错误?
-
调用方法“modifyQuestionStatus”类型错误时出现异常:无法调用未定义的方法“forEach”。
-
看起来
userTrue或userFalse是undefined。你是在什么地方设置的吗?
标签: javascript meteor meteor-helper