user3323307
user3323307

Reputation: 253

Query MongoDB in Meteor "each context" nested

Example:

<template name="list_customers">
  <p><h3>List Customers</h3></p>
  {{#each customers}}
    {{> list_customers_content}}
  {{/each}}
</template>

<template name="list_customers_content">
..display all customer data from "Customers.find({})...

{{> list_customers_content_ip}}

</template>

<template name="list_customers_content_ip">
.. display data from Customers_ip.find({}) based on #each customer object id.
</template>

Template.list_customers.helpers({
  customers() {
    return Customers.find({});
  },
});

How can this be done in fewest possible queries to two different collections, and is there any way to use the customers context object id? Please write full example.

What should the helper for Customers_ip.find() look like?

Upvotes: 0

Views: 33

Answers (1)

Jankapunkt
Jankapunkt

Reputation: 8413

You need to pass the current document (which is this inside the #each context) to the list_customers_content template in order to further process it.

The name of the parameter will be the name to access the value in the child template.

Example:

{
  name: "John Doe",
  _id: "1232131",
}


<template name="list_customers">
  <p><h3>List Customers</h3></p>
  {{#each customers}}
    {{> list_customers_content customer=this}}
  {{/each}}
</template>

<template name="list_customers_content">
  <span>Name: {{customer.name}}</span><!-- John Doe -->
  {{> list_customers_content_ip customerId=customer._id}}
</template>

<template name="list_customers_content_ip">
  {{#each customerIp customerId}}
    <span>IP: {{this.ip}}</span>
  {{/each}}
</template>

A helper for customerIp could look like this:

Template.list_customers_content_ip.helpers({

  customerIp(customerId) {
    // assumes, that these documents have
    // a field named "customerId"
    return Customers_ip.find({ customerId }); 
  },

});

Upvotes: 1

Related Questions