从数组中删除项目不起作用

时间:2015-02-15 10:57:30

标签: javascript mongodb meteor

我正在尝试从数组中删除标记。但我无法让它发挥作用 - 没有任何反应。 console.log输出似乎是正确的。谢谢!

事件处理程序

Template.doc.events({
    'click .remove': function(event, template) {
        console.log("This doc's _id: " + template.data._id);
        console.log("doc's tags: " + template.data.metadata.tags);

        var thisTag = this;
        console.log("thisTag: " + thisTag);

        MyPix.update (
            template.data._id,
            { $pull: { 'template.data.metadata.tags': thisTag }},
            { multi: true }
        );
    },
});

模板

<template name="doc">
    <ol><li>
        <span class="property">metadata.tags</span>: 
        {{#each this.metadata.tags}}
            <span class="tag"><span class="remove">X</  span>{{this}}</span>
        {{/each}}
    </li></ol>
</template>

4 个答案:

答案 0 :(得分:1)

乍一看,看起来拉动中的字段标识符不正确。在这里,您必须使用MongoDB标识符,而不是属于您的对象的标识符。尝试更改

template.data.metadata.tags

metadata.tags
在拉电话中

答案 1 :(得分:1)

尝试使用$push运算符。

Template.doc.events({
    'click .remove': function(event, template) {
        console.log("This doc's _id: " + template.data._id);
        console.log("doc's tags: " + template.data.metadata.tags);

        var thisTag = this;
        console.log("thisTag: " + thisTag);

        MyPix.update (
            template.data._id,
            { $push: { 'template.data.metadata.tags': thisTag }},
            { multi: true }
        );
    },
});

如果你console.log(template.data.metadata.tags)你得到了什么阵列? console.log(template.data.metadata.tags.length)返回什么?

您可能需要查看Array Update Operators

答案 2 :(得分:0)

你可以尝试类似的东西吗?

MyPix.update (
        template.data._id,
        { $pull: { metadata:{ tags: thisTag } } },
        { multi: true }
    );

答案 3 :(得分:0)

事实证明this是一个对象,必须转换为字符串。并且MongoDB标识符必须与$pull一起使用。谢谢指点! @Ethaan&amp; @Mellowlicious

'click .remove': function(event, template) {
    console.log("This doc's _id: " + template.data._id);
    console.log("doc's tags: " + template.data.metadata.tags);

    var thisTag = String(this); // conversion to a string
    console.log("removing thisTag: " + thisTag);

    MyPix.update (
        template.data._id,
        { $pull: { 'metadata.tags': thisTag }}, // MongoDB identifier
    );
}
相关问题