Meteor/Mongo - 如何编写查询以从单独的数据上下文中获取数据

Meteor/Mongo - How to write a query to get data from a separate data context

我有两个单独的集合,PatientsInvoices:

Patients Collection

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


Invoices Collection:

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

我想显示一个显示所有发票的 table。在列中,我想向患者显示发票与之相关(我将 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 和关系数据库,我不禁想知道这是否适合我的特定情况,因为我不完全确定如何执行此查询。我应该改变我的设计吗?

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

例如,如果您要重构您的流星应用程序,您可以按如下方式重新定义您的 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>