我有1个光标来计算选民总数。我有两种方法,首先计算对我有利的选民总数,第二种方法计算投票的总选民数。
LIB / collection.js
infavourcount = new Mongo.Collection('infavourcount');
votedone = new Mongo.Collection('votedone');
SERVER / publish.js [算上有利于我的选民]
function upsertInFavourCount() {
var yes = voters.find({favour: {$regex:"Y", $options: 'i'}}).count();
var maybe = voters.find({favour: {$regex:"M", $options: 'i'}}).count();
var no = total - (yes + maybe);
infavourcount.upsert('infavour',
{
yes: yes ,
maybe: maybe,
no:no
}
);
}
// null name means send to all clients
Meteor.publish(null,function() {
upsertInFavourCount();
return infavourcount.find();
});
SERVER / publish.js [计算成功投票]
function upsertVoteDone() {
var done = voters.find({voted: {$regex:"Y", $options: 'i'}}).count();
votedone.upsert('votedone',
{
done: done
}
);
}
Meteor.publish(null,function() {
upsertVoteDone();
return votedone.find();
});
var cursor = voters.find();
cursor.observe({
changed: upsertVoteDone
});
客户端/模板/ home.js
Template.home.onCreated(function(){
Meteor.subscribe('voters');
Meteor.subscribe('infavourcount');
Meteor.subscribe('votedone');
});
Template.home.helpers({
yesvote : function() {
return infavourcount.findOne().yes;
},
maybevote : function() {
return infavourcount.findOne().maybe;
},
novote : function() {
return infavourcount.findOne().no;
},
votedone : function() {
return votedone.findOne().done;
}
});
我的问题是如何在一个Meteor出版集合的观察方法中调用多个upsert方法。
答案 0 :(得分:0)
顺便说一句,我得到了解决方案。答案是在"更改"或者"添加"或"删除"事件并在其中调用n个upsert方法。
cursor.observe({
changed: function(id, fields){
upsertInFavourCount();
upsertVoteDone();
}
});