Meteor在用户登录前后发布记录

Meteor在用户登录前后发布记录,meteor,Meteor,我的发布功能如下: Meteor.publish('ownedrecords', function() { if (!this.userId) { this.error(new Meteor.Error(500, 'Internal server error')); return; } return Records.find({owner:this.userId}); });

我的发布功能如下:

    Meteor.publish('ownedrecords', function() {
        if (!this.userId) {
            this.error(new Meteor.Error(500, 'Internal server error'));
            return;
        }
        return Records.find({owner:this.userId});
    });
    Meteor.subscribe("ownedrecords")
我在客户端中的订阅方式如下:

    Meteor.publish('ownedrecords', function() {
        if (!this.userId) {
            this.error(new Meteor.Error(500, 'Internal server error'));
            return;
        }
        return Records.find({owner:this.userId});
    });
    Meteor.subscribe("ownedrecords")
但是在用户登录之后,客户端没有得到用户拥有的记录。所以我这样做了:

    Deps.autorun(function() {
            var user = Meteor.userId();
            Meteor.subscribe("ownedrecords");
    }

这就解决了问题。但这是一种标准和推荐做法吗?

当用户登录或注销时,当前/活动订阅将自动重新运行

然后,惯例是在希望发生这种情况的情况下调用
this.ready()

Meteor.publish('ownedrecords', function() {
    if (!this.userId) {
        this.ready();
        return;
    }
    return Records.find({owner:this.userId});
});

当前/活动订阅将在用户登录或注销时自动重新运行

然后,惯例是在希望发生这种情况的情况下调用
this.ready()

Meteor.publish('ownedrecords', function() {
    if (!this.userId) {
        this.ready();
        return;
    }
    return Records.find({owner:this.userId});
});

如果用户未登录,则抛出错误:

因此,客户端将中止订阅,因此当用户登录时,由于订阅不再处于活动状态,他们将无法再获得更新

您需要做的就是避免抛出错误

Meteor.publish('ownedrecords', function() {
    if (!this.userId) return [];

    return Records.find({owner:this.userId});
});

如果返回空光标或激发this.ready(),则应该没有问题。

如果用户未登录,则抛出错误:

因此,客户端将中止订阅,因此当用户登录时,由于订阅不再处于活动状态,他们将无法再获得更新

您需要做的就是避免抛出错误

Meteor.publish('ownedrecords', function() {
    if (!this.userId) return [];

    return Records.find({owner:this.userId});
});
如果您返回一个空光标或激发this.ready(),那么您应该不会有问题。

只需将

Meteor.publish('ownedrecords', function() {
  return Records.find({owner:this.userId});
});
如果没有文档拥有
null
所有者,则应导致正确的行为。

简单地说

Meteor.publish('ownedrecords', function() {
  return Records.find({owner:this.userId});
});

如果没有文档拥有
null
所有者,则应导致正确的行为。

返回
this.stop()
(对于内存管理)不是更好吗?这样,不会创建发布,服务器会释放内存。如果返回
[]
this.ready()
,则有一个出版物(没有数据)会消耗一些内存。我错了吗?
this.stop()
肯定会节省内存,因为它会关闭订阅,即使发布的光标为空,观察者仍会使用内存。我的理解是OP希望订阅在用户登录后立即返回新的相关数据,而不使用
Deps.autorun
,因此它需要保持活动状态。嗯,我很困惑。由于userId来自一个被动上下文,一旦设置了userId,它是否真的会使发布再次处于活动状态?@serkandurosay当用户登录时,订阅会重新运行,但只有当订阅在当时仍然处于活动状态时,这就是必须发送
this.ready()
变体的原因。如果使用了
this.stop()
或抛出错误,那么服务器将丢弃它和它的游标,这样当用户登录时它就不会再次运行了。返回
this.stop()
?这样,不会创建发布,服务器会释放内存。如果返回
[]
this.ready()
,则有一个出版物(没有数据)会消耗一些内存。我错了吗?
this.stop()
肯定会节省内存,因为它会关闭订阅,即使发布的光标为空,观察者仍会使用内存。我的理解是OP希望订阅在用户登录后立即返回新的相关数据,而不使用
Deps.autorun
,因此它需要保持活动状态。嗯,我很困惑。由于userId来自一个被动上下文,一旦设置了userId,它是否真的会使发布再次处于活动状态?@serkandurosay当用户登录时,订阅会重新运行,但只有当订阅在当时仍然处于活动状态时,这就是必须发送
this.ready()
变体的原因。如果使用了
this.stop()
或抛出错误,则服务器将丢弃该错误及其游标,以便在用户登录时不再运行该错误