【问题标题】:meteor publish/subscribe confusion流星发布/订阅混乱
【发布时间】:2014-06-16 18:54:30
【问题描述】:

所以,在我的 server.js 中,我有以下代码来限制客户端接收的内容:

Meteor.publish('customerList', function()
{
    return Meteor.users.find({roles: 'customer'}, {fields: {profile: 1}});
});

我只想使用 Roles 包查找具有价值 'customer' 的 'roles' 的用户。然后在 client.js 我做另一个 find() 订阅:

Meteor.subscribe('customerList', function()
{
    var foundCustomers = Meteor.users.find().fetch();

    Session.set('foundCustomers', foundCustomers); //i have a Session.get elsewhere which returns this cursor
});

当然,在我的模板中,我会像这样显示这些值:

<template name="customer_search_result">
    {{#each customers}}
        <div>{{profile.firstname}} {{profile.lastname}}, {{profile.tel}}</div>
    {{/each}}
</template>

那么当我现在看到此列表中的所有不同角色时,我做错了什么?如果我在订阅的find() 中添加与我发布的相同的规则,那么我们根本不会得到任何结果。

【问题讨论】:

  • 您已删除自动发布包?
  • 是的,没错,我删除了 autopublish 包,因为这是 Roles 抱怨的东西^^
  • 该发布是唯一发布来自Meteor.users 集合的文档的发布?
  • roles 字段包含您要排除的用户的什么内容?是否只是例如['admin'] 还是 ['admin', 'customer'] 之类的? (您可以通过在命令行输入meteor mongo然后执行db.users.find()来检查)
  • No Peppe,还有另一个发布“员工”类型的用户。我想同时发布一个employeeList 和一个customerList。 user3374348,角色只包含一个字符串,如“admin”或“customer”atm。

标签: javascript meteor


【解决方案1】:

您的发布和模板看起来不错,您只需要像这样更改您的订阅:

Meteor.subscribe('customerList');

那么你需要一个像这样的模板助手:

Template.customer_search_result.helpers({
    customers: function(){
        return Meteor.users.find({roles: 'customer'}, {fields: {profile: 1}});
    }
})

【讨论】:

    【解决方案2】:

    由于还有另一个发布employees 的出版物,您只需在订阅回调中从Meteor.users 获取customers,否则您可能还会得到一些employees。首先,将roles 添加到已发布的字段中(我认为这不是问题):

    Meteor.publish('customerList', function()
    {
        return Meteor.users.find({roles: 'customer'}, {fields: {profile: 1, roles: 1}});
    });
    

    然后更新订阅功能:

    Meteor.subscribe('customerList', function()
    {
        var foundCustomers = Meteor.users.find({roles: 'customer'}).fetch();
        Session.set('foundCustomers', foundCustomers);
    });
    

    顺便说一句,通过fetching 光标并将结果存储在会话中,您将破坏反应性。如果这是故意的 - 您只需要客户的一次性快照 - 您应该考虑在完成订阅后停止订阅,否则服务器将继续向客户端发送从未使用过的新客户:

    var customerListSubscription = Meteor.subscribe('customerList', function()
    {
        var foundCustomers = Meteor.users.find({roles: 'customer'}).fetch();
        Session.set('foundCustomers', foundCustomers);
        customerListSubscription.stop();
    });
    

    如果您想要反应性,请参阅 Kelly Copley 的回答。

    【讨论】:

    • 当我记录它时它只返回“[]”,什么都没有
    • 哦,您还必须在已发布的字段中包含roles ({fields: {profile: 1, roles: 1}})。现在,你不发布它,所以客户端不能使用它来find by。
    猜你喜欢
    • 2014-05-04
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2018-12-26
    • 1970-01-01
    相关资源
    最近更新 更多