解析JS SDK:relation.add()不起作用

时间:2016-10-30 22:48:10

标签: javascript parse-platform

我需要在Parse JS SDK中为关系添加对象,但是我无法使relation.add()工作,我无法找到我的代码和我搜索的文档或答案中的示例之间的差异。我的功能:

addTagsToProduct(productId, tags) {
        console.log(productId);
        console.log(tags);
        let query = new this.cloud.parse.Query('Products');
        query.equalTo('objectId', productId);
        query.first().then((product) => {
            console.log(product);
            product.relation('tags').query().find().then((productTags) => {
                console.log(productTags);
                let productTagIds = productTags.map((tag) => {
                    return tag.id;
                });

                tags.forEach((tag) => {
                    console.log('checking', tag);
                    if (productTagIds.indexOf(tag) === -1) {
                        console.log('adding', tag);
                        let query = new this.cloud.parse.Query('Tags');
                        query.equalTo('objectId', productId);
                        query.first().then((tag) => {
                            console.log('found', tag);
                            console.log('relation', product.relation('tags'));

                            product.relation('tags').add(tag);
                            product.relation('tags').save({useMasterKey: true}).then((product) => {
                                console.log('saved', product);
                                product.relation('tags').query().find().then((productTags) => {
                                    console.log(productTags);
                                });
                            });
                        }).catch((err) => {
                            console.error(err);
                        });
                    }
                });
            }).catch((err) => {
                console.error(err);
            });
        });
    }

console.log()的输出结果:

pJ1B9mE34k // product ID
["pJ1B9mE34k", "pJ1B9mg34k"] // tags to add
ParseObject {_objCount: 8, className: "Products", id: "pJ1B9mE34k"} // found product
[ParseObject] // tags already added to relation (manually)
checking pJ1B9mE34k // already added tag
checking pJ1B9mg34k // new tag
adding pJ1B9mg34k // found out it's new, adding
found ParseObject {_objCount: 10, className: "Tags", id: "pJ1B9mE34k"} // found tag by id
relation ParseRelation {parent: ParseObject, key: "tags", targetClassName: "Tags"} // relation to add new object to
saved ParseObject {_objCount: 8, className: "Products", id: "pJ1B9mE34k"} // .then() of save() function
[ParseObject] // one relation, the same as before, new one wasn't saved

我想我错过了一些小细节,但我真的无法找到这些细节,所以任何帮助都会非常感激。 从package.json解析版本:~1.9.2

1 个答案:

答案 0 :(得分:2)

我认为你必须使用

let productTagsRelations = product.relation("tags");
productTagsRelations.add(tag);
product.save();

而不是

product.relation('tags').save();

因为标签是产品文档中的关系数组 - 是列。 所以你必须处理产品对象本身。不是标签col。