2013-09-22 57 views
5

好的,我對Meteor.js有些困惑。我創建了一個網站來測試各種概念,並且它運行良好。一旦我刪除「不安全」和「自動發佈」,當嘗試檢索並推送到服務器時,會出現多個「訪問被拒絕」錯誤。我相信它是與下面的代碼片段: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; 
     } 

    }); 

} 
+0

是的,你聲明變量'Posts',但嘗試在服務器上使用'posts'來訪問它。你應該糾正錯字,因爲你現在有一個問題和答案顯示代碼不會運行。 – user728291

回答

7

好了,有兩個部分這個問題:

自動發佈

要發佈的數據庫中的流星,你需要在項目的服務器端和客戶端都有代碼。假設你已經實例化的集合(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的響應將意味着「不允許此操作」

希望這回答你所有的問題

+0

當你說'insert:function(userId,document)'或'update:function(userId,doc,fieldNames,modifier)'時,你如何傳遞這些參數?而且,你是否從客戶端或服務器那裏這樣做? –

+1

你不會調用這些函數本身。他們在某些事件中被流星所調用,並通過調用者的這些參數。這有意義嗎? – Zwade

+0

Mmkay,所以他們被某些事件調用......但我不確定我是否理解這些參數是如何傳遞的。你能否提供(或鏈接)一個客戶端代碼觸發insert/update/remove函數並傳遞參數的例子? –