【问题标题】:Meteor/Mongo - How to write a query to get data from a separate data contextMeteor/Mongo - 如何编写查询以从单独的数据上下文中获取数据
【发布时间】:2016-12-10 04:56:03
【问题描述】:

我有两个单独的集合,PatientsInvoices

Patients Collection

{
  first_name: ...
  surname: ...
  ...
}


Invoices Collection:

{
  invoice_no: ...
  patient_id: ...
  ...
}

我想显示一个显示所有发票的表格。在这些列中,我想向患者展示与发票相关的内容(我将patient_id 作为Invoices 集合中的字段之一)。

所以我有这个助手:

Template.showInvoices.helpers({
  invoices: function () {
    return Invoices.find(); // i know this isn't ideal.
  }
});

这是模板:

<template name="showInvoices">
  {{#each invoices}}
    <tr>
      <td>{{invoice_no}}</td>
      <td> [PATIENT NAME] </td>
    </tr>
  {{/each}}
</template>

如何从发票数据上下文中获取患者姓名?来自 MySQL 和关系数据库,我不禁想知道这是否适合我的特殊情况,因为我不完全确定如何执行此查询。我应该改变我的设计吗?

【问题讨论】:

    标签: html mongodb meteor meteor-blaze


    【解决方案1】:

    您可以利用定义集合时可用的可选转换函数transform。 transform 选项是一个以文档为参数并且可以修改的函数。文档将在从fetchfindOne 返回之前通过此函数,并在传递给observemapforEachallowdeny 的回调之前,因此这将允许您可以嵌入与连接同义的另一个集合中的数据。

    例如,如果您要重构您的流星应用程序,您可以重新定义您的Invoices 集合,如下所示:

    Invoices = new Mongo.Collection('invoices', {
        transform: function(doc) {
            doc.patient = Patients.findOne(doc.patient_id);
            return doc;
        }
    });
    

    现在,当您在助手中调用 Invoices.find().fetch() 时,您将可以访问 patient 属性,这是一个 Patient 文档:

    Template.showInvoices.helpers({
        invoices: function () {
            return Invoices.find().fetch(); 
        }
    });
    

    模板

    <template name="showInvoices">
        {{#each invoices}}
            <tr>
                <td>{{invoice_no}}</td>
                <td>{{patient.first_name}}</td>
            </tr>
        {{/each}}
    </template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多