I need help with the line for meteor that updates multiple entries in the database. The first Entries.update below does not work I believe because meteor now requires you to update by id.
'click #draw': ->
winner = _.shuffle(Entries.find(winner: {$ne: true}).fetch())[0]
if winner
Entries.update({recent: true}, {$set: {recent: false}}, {multi: true})
Entries.update(winner._id, $set: {winner: true, recent: true})
Template.entry.winner_class = ->
if this.recent then 'highlight' else ''
So I tried to change to the below code. However, it does not work properly since it appears as it only changes one id (the first one).
'click #draw': ->
winner = _.shuffle(Entries.find(winner: {$ne: true}).fetch())[0]
recent_winner = Entries.find(recent: true).fetch()
if winner
Entries.update(recent_winner._id, {$set: {recent: false}}, {multi: true})
Entries.update(winner._id, $set: {winner: true, recent: true})
Template.entry.winner_class = ->
if this.recent then 'highlight' else ''
Any help would be appreciated.
You will need to modify multiple docs at once via Meteor.methods. From the documentation:
The behavior of update differs depending on whether it is called by trusted or untrusted code. Trusted code includes server code and method code. Untrusted code includes client-side code such as event handlers and a browser's JavaScript console.
Trusted code can modify multiple documents at once by setting multi to true, and can use an arbitrary Mongo selector to find the documents to modify. It bypasses any access control rules set up by allow and deny. The number of affected documents will be returned from the update call if you don't pass a callback.
Untrusted code can only modify a single document at once, specified by its _id. The modification is allowed only after checking any applicable allow and deny rules. The number of affected documents will be returned to the callback. Untrusted code cannot perform upserts, except in insecure mode.
EDIT:
By way of example, a method call might look something like this:
"click #draw": function(){
var winner = _.shuffle(Entries.find({winner: {$ne: true}}).fetch())[0];
if (!!winner){
Meteor.call(
"drawWinner", //an arbitrary method name of your choosing
winner, // passing it your winner
function(error, result){ // an optional async callback
if (error){
// handle error if error from method
} else {
// handle any return object from method
}
}
);
}
}
And then in your method call, which might be placed in a shared directory such as 'lib' or in a server side-only directory (see the Meteor documentation for more on this point):
Meteor.methods({
"drawWinner": function(winner){
Entries.update({recent: true}, {$set: {recent: false}}, {multi: true});
Entries.update(winner._id, {$set: {winner: true, recent: true}});
return winner; //or the like
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With