How to retireve an embedded document within a template helper?


#1

I need to run a find on a particular mongo collection and retrieve a particualr value which is embedded. I tried running the raw query on mongo directly and it works. However, when I try it from within the template helper, I seem to run into syntax errors. Can someone show me the right syntax?

Sample collection:

{
name: a,
age: 10,
address: { 
            street: X,
            area: Y
    }
}

I need to search using street and arrive with area.

db.Collection.find( name:a, age:10, “address.street”: X) --> This fetches the entire record in mongo shell.

But when I try the same in a helper, I run into syntax errors. I’ve tried address[‘street’] , address:{street: X} but to no success.

Could someone show me how it’s done?

Thanks


#2

Something like the following should work:

const widget = Widgets.findOne({
  name: 'Test Widget',
  age: 100,
  'address.street': '123 Widget Way'
});

#3

What I did is mapped the query such that I ended up with an array of objects. Now, I need to find only a subset within this array of objects and return it to {{#each}} but it somehow seems that _.find isn’t returning any array.

var result = Collection.find({....}).map(....);

result currently contains:

result = [{key: A, value: 'foo'}, {key: A, value:'bar'},{key: B, value:'bar}]

Then I did:

result2 = _.find(result, function(obj) { return obj.name == A });

However, when I return result2, I get the following error:

Error: {{#each}} currently only accepts arrays, cursors or falsey values.

How exactly do I return all value for which key is A?


#4

That doesn’t look right. Do you mean:

result = [{key: 'A', value: 'foo'}, {key: 'A', value:'bar'}, {key: 'B', value:'bar'}]

?


#5

Apologies. I fixed my typo. Yes, it’s

result = [{key: 'A', value: 'foo'}, {key: 'A', value:'bar'}, {key: 'B', value:'bar'}]


#6

Okay, I actually got it to work using _.where. Buit for my knowledge perspective, how else can this be achieved?

Thanks


#7

You could try the array .filter method:

Do this from your result array (result.filter(...)), or with Collection.find().fetch().filter(...).