2015-12-17 50 views
0

與收藏FruitsMeteor.users一個測試應用程序,用戶點擊一個水果的名稱,將其添加到自己的收藏夾列表,使用服務器端代碼與Collection.find無功更新流星

Meteor.users.update(Meteor.user()._id, { $push: {'profile.favorites': fruit_id } }) 

其中fruit_id是由Mongo生成的ObjectID fruit._id

有關喜愛的水果網頁,客戶端還簽約有出版:

Meteor.publish('favoriteFruits', function() { 

    return Fruits.find({ 
     '_id': { 
      '$in' : Meteor.users.findOne(this.userId).profile.favorites 
     } 
    }) 

} 

問題:當一個新的水果製成的最愛,沒有最喜歡的水果頁面上的變化,除非頁面刷新制作。

我的猜測是因爲在發佈代碼中,包含$in的行不是被動的。

對於這種情況,通常的做法是讓用戶反應性地看到新添加或去除的水果? Meteor.users.findOne(this.userId).profile.favorites可以做出反應嗎?


訂閱在控制器中完成,我正在使用Angular和Meteor。

angular.module('myApp').controller('FavoriteFruitsCtrl', function($scope, $meteor) { 

    $meteor.autorun($scope, function() { 

     $meteor 
      .subscribe('favoriteFruits') 
      .then(function() { 
       $scope.favfruits = $meteor.collection(Fruits, false) 
      }) 

    }) 

}) 

基於由@SylvainB和@Billybobbonnet的建議,我們試圖做到這一點?包含.subscribe的第二個自動運行會在Meteor.user().profile.favorites發生更改時重新運行!

angular.module('myApp').controller('FavoriteFruitsCtrl', function($scope, $meteor) { 

    $meteor.autorun($scope, function() { 
     Session.set('favorites', Meteor.user().profile.favorites) 
    }) 

    // This autorun block will be triggered when the above autorun is triggered 
    $meteor.autorun($scope, function() { 
     var justForTriggering = Session.get('favorites') 
     $meteor 
      .subscribe('favoriteFruits') 
      .then(function() { 
       $scope.favfruits = $meteor.collection(Fruits, false) 
      }) 
    }) 

}) 

但是$meteor.subscribe功能不解僱(由服務器端的檢查)

+0

你能告訴我們你的訂閱是如何以及在哪裏完成的?它基本上歸結爲使您的訂閱反應到'Meteor.user()' – SylvainB

+0

@SylvainB我已經更新了問題的方式訂閱目前正在完成 – Nyxynyx

回答

0

我會用最喜歡的水果作爲參數的陣列創建一個template level subscription。它假定您在另一個出版物中公開profile.favorite字段,但它應該已經默認公開給當前用戶。

由於您將自動套用您的訂閱並使用用戶集合中的光標,因此事件的大小如下: 更新配置文件>觸發自動運行>更新最喜歡水果的發佈。

+0

是的,甚至不需要使用最喜歡的水果數組(這樣他或她可以在服務器端保持這種檢查,我猜測這是需要的)。只需檢查用戶何時更新。如果你想更具體,[看這裏](http://stackoverflow.com/a/29753793/1439597)。 – SylvainB

+0

@davidweldon的另一個不錯的訣竅。謝謝你提到它。 – Billybobbonnet