【问题标题】:Can't update multiple records in a collection? [duplicate]无法更新集合中的多条记录? [复制]
【发布时间】:2015-09-25 19:57:13
【问题描述】:

我不断收到此错误:

Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]

这里是代码:

Template.notifications.events({
   'click a.clearAll':function(event){
    console.log("hey");
    Notifications.update({{userId:Meteor.userId()},{$set:{read:true}},{multi:true});
 }
})

我还设置了更新权限:

Notifications.allow({
  insert: function(){
 return true;
 },
 update: function(){
return true;
 }
});

为什么不让我更新?

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    此错误的原因是因为您正在从客户端进行更新,这被服务器视为'不受信任的代码'

    除非您还没有删除不安全的包并且没有制定任何权限规则,否则它会起作用。我建议始终删除 meteor remove insecure 的不安全包并进行方法/调用以执行客户端发起的服务器功能是一个好习惯。

    你需要从客户端到服务端创建一个'call',并在methods函数内部执行更新命令。

    客户:

    Template.notifications.events({
       'click a.clearAll':function(event){
            Meteor.call('updateDocs',
                function(error, result) {
                    if (error) {
                        console.log(error);
                    }
                    else {
                        console.log('done');
                    }
                });
        }
    });
    

    服务器:

    Meteor.methods({
        updateDocs: function() {
            var userId = this.userId
            if (userId) {
                Notifications.update({{userId: userId},{$set:{read:true}},{multi:true});
            }
            return;
        }
    });
    

    【讨论】:

      【解决方案2】:

      @meteorBuzz 是正确的。如果您仍希望从客户端更新,您可以使用forEach

      Notifications.find({ userId:Meteor.userId() }).forEach(function(n){
        Notifications.update({ _id: n._id },{$set:{ read:true }});
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-08
        • 1970-01-01
        • 2020-12-29
        • 1970-01-01
        • 2017-09-14
        • 1970-01-01
        • 2019-02-18
        相关资源
        最近更新 更多