在 onBefore 钩子或类似钩子中更改返回的集合

Altering a returned collection in onBefore hook or similar hook

是否可以在 onBeforeAction 或类似挂钩中更改(为每条记录添加更多字段)返回的集合?

我有正在分页的 InvoiceHistory 集合。我还想在每张发票中显示公司名称、公司地址、电子邮件地址和增值税注册号——这四个字段存储在另一个集合中。所以我想将这四个字段添加到从 InvoiceHistory 返回的每条记录中。如果有另一种方法可以做到这一点,我愿意接受建议。我正在使用 Alethes 流星分页,当您 navigate/browse/page 到第二页时,它会丢失其 itemTemplate 中返回的辅助字段。 Alethes分页也依赖iron-router,是否可以借助iron-router实现我想要的

============================================= ===========================

@肖恩。谢谢。下面是使用 meteor publish composite 的代码:

if (Meteor.isServer) {

 import { publishComposite } from 'meteor/reywood:publish-composite';

 publishComposite('invoicesWithCompanyDetails', function(userId, startingDate,endingDate) {
  return {
   find() {
    // Find purchase history for userId and the two dates that were entered. Note arguments for callback function
    // being used in query.
    return PurchaseHistory.find({Id:userId,transactionDate:{$gte:new Date(decodeURIComponent(startingDate)),
       $lt:new Date(decodeURIComponent(endingDate))}});
   },
   children: [
    {
   
     find() {
      return CompanySharedNumbers.find(
       { _id:"firstOccurrence" },
       { fields: { companyName: 1, companyAddress: 1 } }
      );
     }
    }
   ]
  }
 });
}

Router.route('/store/invoices/:_username/:startingDate/:endingDate', { //:_startingDate/:_endingDate
 name: 'invoices',
 template: 'invoices',
 onBeforeAction: function()
 {
  ...
 },
 waitOn: function() {
  var startingDate = this.params.startingDate;
  var endingDate = this.params.endingDate;
  return [Meteor.subscribe('systemInfo'),Meteor.subscribe('testingOn'),Meteor.subscribe('invoicesWithCompanyDetails',startingDate,endingDate)];
 } 
});

Pages = new Meteor.Pagination(PurchaseHistory, {
 itemTemplate: "invoice",
 availableSettings: {filters: true},
 filters: {},
 route: "/store/invoices/:_username/:startingDate/:endingDate/",
 router: "iron-router",
 routerTemplate: "invoices",
 routerLayout: "main",
 sort: {
  transactionDate: 1
 },
 perPage: 1,
 templateName: "invoices",
 homeRoute:"home"
});

如果我没听错的话,这听起来像是 composite publication 的工作。

使用复合出版物,您可以同时 return 来自多个集合的相关数据。

因此,您可以找到所有发票,然后使用存储在发票对象中的公司 ID,您可以 return 同时从公司集合中 return 公司名称和其他信息。

我以前对复杂的数据结构使用过复合出版物,它们工作得很好。

希望对您有所帮助

而不是向所有文档添加新字段。您可以做的是添加一个帮助程序来加载公司文档:

Template.OneInvoice.helpers({
    loadCompany(companyId){
        return Company.findOne({_id: companyId});
    }
});

并在您的模板代码中使用它:

<template name="OneInvoice">
    <p>Invoice id: {{invoice._id}}</p>
    <p>Invoice total: {{invoice.total}}</p>
    {{#let company=(loadCompany invoice.companyId)}}
        <p>Company name: {{company.name}}</p>
        <p>Company business address: {{company.businessAddress}}</p>
    {{/let}}
</template>

这样一来,代码就非常简单,易于维护。