I have some documents in my base:
//example docs
{"_id": "qwerty12345", "name": "Bob", "cards":["cardId1", "cardId2", "cardId3"]}
I'm using this for inserting data:
Template.insert.events({
'click add': function(){
if(confirm("Add card?"));
mycollection.update({_id: Session.get('fooId')}, { $addToSet: { cards: this._id}})
}
});
Then i'm using this helper for my template:
Template.index.helpers({
cards: function(){
query = mycollection.findOne({_id: Session.get('fooId')});
return query.cards;
}
});
And in template:
<img src="{{img}}" class="add">
{{#each cards}}
{{this}}<br>
{{/each}}
This works perfecty, but i have a trouble:
As you see, every image have id and url({{image}}), i'm need to add image url to 'mycollection' too for every card(on click).
How to make it?
And the second problem: How to allow mongo insert duplicates to "cards" array?
Do you mean every card has id and image field? I guess so.
You can add nested object to an array fields. Like that
mycollection.update({_id: Session.get('fooId')}, { $addToSet: { cards: {id: this._id, image: this.image}}})
.
In the template:
{{#each cards}}
{{this.id}}: {{this.image}}<br>
{{/each}}
For second problem: You can use $push
instead of $addToSet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With