[英]Meteor.js Publishing and Subscribing?
好的,所以我對Meteor.js的某些事情感到困惑。 我用它創建了一個網站來測試各種概念,它運行良好。 一旦我刪除了“不安全”和“自動發布”,我在嘗試檢索並推送到服務器時會收到多個“拒絕訪問”錯誤。 我相信它與以下代碼段有關:
Template.posts.posts = function () {
return Posts.find({}, {sort: {time: -1}});
}
我認為它正在嘗試直接訪問該集合,允許它啟用“不安全”和“自動發布”,但是一旦它們被禁用,它就會被拒絕訪問。 我認為另一件作品存在問題:
else {
Posts.insert({
user: Meteor.user().profile.name,
post: post.value,
time: Date.now(),
});
我認為同樣的事情正在發生:它試圖直接訪問集合,這是不允許的。
我的問題是,我如何重新考慮它,以便我不需要啟用“不安全”和“自動發布”?
謝謝。
編輯
最后:
/**
* Models
*/
Posts = new Meteor.Collection('posts');
posts = Posts
if (Meteor.isClient) {
Meteor.subscribe('posts');
}
if (Meteor.isServer) {
Meteor.publish('posts', function() {
return posts.find({}, {time:-1, limit: 100});
});
posts.allow({
insert: function (document) {
return true;
},
update: function () {
return false;
},
remove: function () {
return false;
}
});
}
好的,這個問題有兩個部分:
自動發布
要在meteor中發布數據庫,您需要在項目的服務器端和客戶端都有代碼。 假設你已經實例化了該集合( Posts = new Meteor.Collection('posts')
),那么你需要
if (Meteor.isServer) {
Meteor.publish('posts', function(subsargs) {
//subsargs are args passed in the next section
return posts.find()
//or
return posts.find({}, {time:-1, limit: 5}) //etc
})
}
然后為客戶
if (Meteor.isClient) {
Meteor.subscribe('posts', subsargs) //here is where you can pass arguments
}
不安全
不安全的目的是允許客戶端不加選擇地添加,修改和刪除它想要的任何數據庫條目。 但是,大多數時候你不希望這樣。 刪除不安全后,您需要在服務器上設置規則,詳細說明誰可以執行哪些操作。 這兩個函數是db.allow和db.deny。 例如
if (Meteor.isServer) {
posts.allow({
insert:function(userId, document) {
if (userId === "ABCDEFGHIJKLMNOP") { //e.g check if admin
return true;
}
return false;
},
update: function(userId,doc,fieldNames,modifier) {
if (fieldNames.length === 1 && fieldNames[0] === "post") { //they are only updating the post
return true;
}
return false;
},
remove: function(userId, doc) {
if (doc.user === userId) { //if the creator is trying to remove it
return true;
}
return false;
}
});
}
同樣,db.deny的行為方式完全相同,但響應為true
意味着“不允許此操作”
希望這能回答你所有的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.