0

I am tryng to create posts using a for loop, but when i look at Parse database only the last object of my array get's stored. this is the code i wrote.

var Reggione = Parse.Object.extend("Reggione");
    var creaReggione = new Reggione();
    var selectobject = $('#searcharea')[0]; 

    for (var i = 2; i < selectobject.length; i++) {

        creaReggione.set("name", selectobject.options[i].text);
        creaReggione.save();

Thanks, Bye.

2 Answers 2

1

Do this by creating an array of new objects, then save them together...

var newObjects = [];
for (var i = 2; i < selectobject.length; i++) {

    creaReggione.set("name", selectobject.options[i].text);
    newObjects.push(creaReggione);
    // ...
}
Parse.Object.saveAll(newObjects);

Remember, if you want something to happen after saveAll completes (like call response.success() if you're in cloud code), then you should use that promise as follows...

Parse.Object.saveAll(newObjects).then(function(result) {
    response.success(result);
}, function(error) {
    response.error(error);
});
Sign up to request clarification or add additional context in comments.

Comments

0

In extension to danhs answer, the reason this does not work is because only one transaction can happen at a time from the JS client to Parse.

Therefore in your loop the first call to .save() is made and the object is saved to Parse at some rate (asynchrounously), in that time the loop continues to run and skips over your other save calls, these objects are NOT queued to be saved. As Danh pointed out, you must use Parse's batch operations to save multiple objects to the server in one go, to do this you can:

var newObjects = [];
for (var i = 2; i < selectobject.length; i++) {

    creaReggione.set("name", selectobject.options[i].text);
    newObjects.push(creaReggione);
    // ...
}
Parse.Object.saveAll(newObjects);

Hope this helps, I'd also recommend taking a look at Parse's callback functions on the save method to get more details on what happened (you can check for errors and success callbacks here to make debugging a little easier)

An example of this would be to extend the previous call with:

Parse.Object.saveAll(newObjects, {
        success: function(messages) {
            console.log("The objects were successfully saved...")
        },
        error: function(error) {
            console.log("An error occurred when saving the messages array: %s", error.message)
        }
    })

I hope this is of some help to you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.