Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor & Mongo: addToSet inserting

Tags:

meteor

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?

like image 593
bartezr Avatar asked Sep 28 '22 05:09

bartezr


1 Answers

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

like image 93
9 revs Avatar answered Oct 10 '22 03:10

9 revs