繁体   English   中英

在Meteor中没有Collection.find的反应式更新

[英]No Reactive Update with Collection.find in Meteor

在具有FruitsMeteor.users集合的测试应用中,用户使用服务器端代码单击水果的名称以将其添加到他最喜欢的列表中

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的建议,我们是否要这样做? 每当Meteor.user().profile.favorites发生更改时,包含.subscribe的第二个自动运行都会重新运行!

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函数(通过在服务器端进行检查)

我将使用喜欢的水果数组作为参数来创建模板级别的订阅 它假定您在另一个出版物中公开了profile.favorite字段,但是默认情况下,当前用户应该已经公开了它。

由于您会将订阅包装在自动运行中,并使用用户集合中的光标,因此事件的原因如下:更新配置文件>触发自动运行>更新喜欢的水果的发布。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM