Meteor:根据id's更新数据库中的多个条目

Meteor: Update multiple entries in a database by their id's

本文关键字:数据库 更新 根据 id Meteor      更新时间:2023-09-26

我需要帮助更新数据库中的多个条目的流星行。第一个条目。下面的更新不工作,我相信,因为流星现在需要你通过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 ''

所以我试着改成下面的代码。然而,它不能正常工作,因为它看起来只改变了一个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 ''

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

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

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

不受信任的代码一次只能修改单个文档,由_id。只有检查出有,才允许修改适用的允许和拒绝规则。受影响文件的数量将被返回回调。不受信任的代码不能执行反转,不安全模式除外。

编辑:

例如,一个方法调用可能看起来像这样:
"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
        }
      }
    );
  }
}

然后在你的方法调用中,它可能被放置在一个共享目录中,比如'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
  }
});