Meteor:通过 ID 更新数据库中的多个条目

Sea*_*n L 4 javascript meteor

我需要有关更新数据库中多个条目的流星行的帮助。我相信下面的第一个 Entries.update 不起作用,因为meteor 现在要求您通过 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 ''
Run Code Online (Sandbox Code Playgroud)

所以我试着改成下面的代码。但是,它无法正常工作,因为它看起来只更改了一个 id(第一个)。

'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 ''
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。

Jer*_* S. 6

您需要通过 Meteor.methods 一次修改多个文档。从文档

update 的行为取决于它是由受信任的代码还是不受信任的代码调用。可信代码包括服务器代码和方法代码。不受信任的代码包括客户端代码,例如事件处理程序和浏览器的 JavaScript 控制台。

可信代码可以通过将 multi 设置为 true 来一次修改多个文档,并且可以使用任意的 Mongo 选择器来查找要修改的文档。它绕过由允许和拒绝设置的任何访问控制规则。如果您不传递回调,将从更新调用中返回受影响文档的数量。

不受信任的代码一次只能修改单个文档,由其 _id 指定。只有在检查任何适用的允许和拒绝规则后才允许修改。受影响的文档数量将返回给回调。不受信任的代码不能执行 upsert,除非在不安全模式下。

编辑:

例如,方法调用可能如下所示:

"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
        }
      }
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的方法调用中,它可能被放置在一个共享目录中,比如“lib”或一个服务器端目录中(有关这一点的更多信息,请参阅 Meteor 文档):

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
  }
});
Run Code Online (Sandbox Code Playgroud)