在for循环中保存Parse对象会保存所有对象

时间:2015-04-08 00:40:55

标签: parse-platform cloud-code

我有以下代码,我试图保存电影的个性。只有少数人物被创造和保存。

var query = new Parse.Query(Movie);

query.find({ success: function(movies) {
    console.log("movies.length " + movies.length );
    for (var movieIterator = 0; movieIterator < movies.length ; movieIterator++) {

        cast_array = movies[movieIterator].get("cast");
        console.log(cast_array);

        for (var i = 0; i < cast_array.length; i++) {
            var personalityObj = new Personality();
            personalityObj.set('name', cast_array[i].trim());
            personalityObj.save();  // NOt all personalities get saved
        }

    }
    response.success("Awesome");
}, error: function(error) {
    response.error(error)
}});

我如何改进代码,以便将所有个性存储/保存在数据库中。

1 个答案:

答案 0 :(得分:3)

你可以尝试一下,让我知道它是否有效。

var query = new Parse.Query(Movie);

query.find({ success: function(movies) {
    console.log("movies.length " + movies.length );
    var list = [];
    for (var i = 0; i < movies.length ; i++) {

        cast_array = movies[i].get("cast");
        console.log(cast_array);

        for (var j = 0; j < cast_array.length;j++) {
            var personalityObj = new Personality();
            personalityObj.set('name', cast_array[j].trim());
            list.push(personalityObj);
        }

    }
    Parse.Object.saveAll(list).then(function(results){
        console.log("Objects were saved!");
        response.success("Awesome");
    },function(eerror){
        console.log(eerror);
        response.error(eerror);
    });

}, error: function(error) {
    response.error(error);
}});

上面的代码使用saveAll函数进行批处理操作。 Docs