【问题标题】:How to find one collection item by an arbitrary property, but not _id, in Meteor?如何在 Meteor 中通过任意属性而不是 _id 找到一个集合项?
【发布时间】:2015-12-03 00:01:30
【问题描述】:

我有一个使用 Flow Router 及其发布/订阅机制的应用程序。我还有一个集合和模板助手。代码在客户端

Template.theCase.helpers({
    theCase: function () {
        var id = FlowRouter.getParam('id');
        var theCase = Cases.findOne({
            id: id
        });

        return theCase;
    }
});

{{#with theCase}}
  {{ id }}
{{/with}}

然后,在服务器上

Meteor.publish('theCase', function (id) {
    return Cases.findOne({
        id: id
    });
});

最后,在两者上 (lib)

FlowRouter.route('/case/:id', {
    subscriptions: function (params) {
        this.register('theCase', Meteor.subscribe('theCase', params.id));
    },
    action: function (params, queryParams) {
        return BlazeLayout.render('container');
    }
});

在我看来,问题在于帮助程序返回undefined,因为它不允许通过_id 以外的任何其他属性在集合中查找项目。我怎样才能克服它?我已经阅读了大量关于 pub/sub、helpers 和 routing 的官方文档,但我找不到解决方案。有什么建议吗?

【问题讨论】:

    标签: javascript mongodb meteor publish-subscribe minimongo


    【解决方案1】:

    您可以按任何字段查询。助手返回 undefined 因为它没有找到任何匹配的东西。

    这段代码有问题:

    Meteor.publish('theCase', function (id) {
        return Cases.findOne({
            id: id
        });
    });
    

    应该是:return Cases.find({id: id});

    出版物必须返回游标或调用this.ready()

    【讨论】:

    • 我遇到的问题正是因为我想使用自定义身份而不是 mongo 生成的_id。我有一个本质上是一个数字的属性,它会递增。我知道这可能是反模式,但这正是我要攻击的问题。
    • 使用 id 可能是有原因的。这不是问题。我刚刚编辑了我的答案。我建议您打印日志以查看您实际期望找到的内容是否存在。
    • 我发现您的出版物有问题并编辑了我的答案
    • 你是对的,Cases.find({...}) 没有返回任何值,因为id 是字符串。只需将其转换为 Number 即可解决问题。我很笨。
    猜你喜欢
    • 2012-09-06
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2014-09-16
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多