Reputation: 447
I have the following example of data set:
SampleCol.insert({
Name: "John Doe",
Description: "Nice Guy",
Embedded_1: [{
key1: 'x1',
key2: 'x2',
TariffTypes: [{
TariffCode: 'Promocional',
Price: 125,
Weekdays: ['Sun', 'Sat']
},
{
TariffCode: 'LastMinute',
Price: 150,
Weekdays: ['Sun', 'Sat']
}],
},
{
key1: 'x3',
key2: 'x4',
TariffTypes: [{
TariffCode: 'Promocional',
Price: 175,
Weekdays: ['Sun', 'Sat']
},
{
TariffCode: 'LastMinute',
Price: 200,
Weekdays: ['Sun', 'Sat']
}]
}]
});
I am trying to filter and show on my template only Embedded_1 with key1='x1'. Here is the template:
<template name="test2">
{{#each items}}
{{# each Embedded_1}}
{{this.key1}}
{{/each}}
{{/each}}
</template>
I tried the following and the Template helper versions:
Version 1 is returning both x1 and x3:
Template.test2.helpers({
items: function () {
collection = SampleCol.find({'Embedded_1.key1': 'x1'});
return collection;
}
});
This also returns all results:
collection = SampleCol.find({Embedded_1: {$elemMatch: { key1: 'x1'}}});
The exit in both cases is: x1x3
It should show only x1.
Where is the error?
EDIT: I have followed answers suggested by Mark Leiber and BraveKenny and they help solve the Mongodb output . I can get now on Mogo shell the desired outcome with the following command:
db.SampleCol.find({},{_id:0, Embedded_1: {$elemMatch: {key1:"x1"}}})
This solves the Mongo part. However, I guess that this problem is also related on HOW this results interact with Meteor Blaze's template. Template "test2" keeps showing up the entire collection rather than what we just filtered.
Any hints there?
EDIT #2 This is indeed a Blaze template issue. The Mongo find() code above correctly returns only the key='x1' results. It even strips out the parent document and data such as name and description:
{
Embedded_1: [{
key1: 'x1',
key2: 'x2',
TariffTypes: [{
TariffCode: 'Promocional',
Price: 125,
Weekdays: ['Sun', 'Sat']
},
{
TariffCode: 'LastMinute',
Price: 150,
Weekdays: ['Sun', 'Sat']
}],
};
However, the template only shows any result if written like below, including the {{#each items}} {{/each}} line
<template name="test2">
{{#each items}}
{{Name}} <br>
{{Description}}<br>
{{#each Embedded_1}}
{{this.key1}} <br>
{{#each TariffTypes}}
{{this.Price}} <br>
{{/each}}
{{/each}}
{{/each}}
</template>
Despite the template helper is not returning Name and Description, it does show them on browser together. It shows like this:
John Doe
Nice Guy
x1
125
150
x3
175
200
I have tester taking out {{#each items}} or {{#each Embedded_1}} and none worked.
How would the Template Blaze should be written?
Upvotes: 0
Views: 172
Reputation: 3250
This should return only the embedded document:
SampleCol.find({Embedded_1: {$elemMatch:{key1:'x3'}}}, {fields: {Embedded_1: true}})
Upvotes: 0