Meteor&Mongo:addToSet插入

bar*_*ezr 5 meteor

我的基地里有一些文件:

//example docs
{"_id": "qwerty12345", "name": "Bob", "cards":["cardId1", "cardId2", "cardId3"]}
Run Code Online (Sandbox Code Playgroud)

我用它来插入数据:

Template.insert.events({
    'click add': function(){
        if(confirm("Add card?"));
        mycollection.update({_id: Session.get('fooId')}, { $addToSet: { cards: this._id}})

    }
});
Run Code Online (Sandbox Code Playgroud)

然后我使用这个帮助器作为我的模板:

Template.index.helpers({
  cards: function(){
        query = mycollection.findOne({_id: Session.get('fooId')});
        return query.cards;
    }
});
Run Code Online (Sandbox Code Playgroud)

在模板中:

<img src="{{img}}" class="add">
{{#each cards}}
{{this}}<br>
{{/each}}
Run Code Online (Sandbox Code Playgroud)

这很完美,但我遇到了麻烦:

如您所见,每张图片都有id和url({{image}}),我需要为每张卡片(点击时)添加图片网址到'mycollection'.

怎么做?

第二个问题:如何允许mongo插入重复到"卡"数组?

小智 4

你的意思是每张卡都有 id 和 image 字段吗?大概吧。

您可以将嵌套对象添加到数组字段。像那样

mycollection.update({_id: Session.get('fooId')}, { $addToSet: { cards: {id: this._id, image: this.image}}})

在模板中: {{#each cards}} {{this.id}}: {{this.image}}<br> {{/each}}

$push对于第二个问题:您可以使用$addToSet