2014-06-11 114 views
1

在我的應用程序中,用戶可以選擇刪除他所有的通知。作爲事件處理程序我有這樣的:刪除記錄userId不允許

Template.clearNotifications.events({ 
    'click .clear-notifications': function() { 
    Notifications.remove({userId: Meteor.user()._id}); 
    } 
}); 

當它被調用時,我得到這個錯誤:

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

這是一個允許我忘了補充,或者是一般不允許這樣做?如果是這樣,我有什麼選擇刪除用戶的通知?

回答

1

在客戶端,流星只允許通過id刪除文件。幸運的是有一個簡單的解決方案 - 只是遍歷當前所有用戶的通知,並刪除每一個:

Template.clearNotifications.events({ 
    'click .clear-notifications': function() { 
    Notifications 
     .find({userId: Meteor.userId()}) 
     .forEach(function(notification) { 
     Notifications.remove(notification._id); 
     }); 
    } 
}); 

請記住,這隻會刪除該客戶端知道的通知(那些已出版)。如果數據庫中還有其他通知需要刪除(也許您只發布了最近的10個文檔),則需要使用method。例如:

Meteor.methods({ 
    removeAllNotifications: function() { 
    Notifications.remove({userId: this.userId}); 
    } 
}); 

,您可以從客戶端調用:

Meteor.call('removeAllNotifications'); 
+0

感謝戴夫,這正是我所期待的。我不知道從客戶端刪除只會刪除發佈的! – John

0

在不受信任的區域(客戶端)拆卸工作,只有當你通過_id的文件

var notification = Notifications.findOne({userId:Meteor.userId()}); 
Notifications.remove({_id:notification._id}) 

說明:

The behavior of remove 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 use an arbitrary Mongo selector to find the documents to remove, and can remove more than one document at once by passing a selector that matches multiple documents. It bypasses any access control rules set up by allow and deny. The number of removed documents will be returned from remove if you don't pass a callback.

As a safety measure, if selector is omitted (or is undefined), no documents will be removed. Set selector to {} if you really want to remove all documents from your collection.

Untrusted code can only remove a single document at a time, specified by its _id. The document is removed only after checking any applicable allow and deny rules. The number of removed documents will be returned to the callback.

http://docs.meteor.com/#remove

+0

OK,但如果我有多個通知,我怎麼重複呢? – John

+0

可信代碼(服務器端)可以做到這一點。在服務器端創建方法,刪除任意Mongo選擇器選擇的通知。 –