几天来,我一直试图弄清楚如何让 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 是存储硬币的数组。
我知道代码并不完美,但我想在清理之前让代码正常工作。我想我提供了足够的信息。我是编程新手,所以如果我遗漏任何有助于回答问题的内容,请告诉我。