1

I am trying to save an array of objects in MongoDB using node.js express and mongoose (MEAN stack). However, when I make the http post requests on the front end for each item in the array, they don't show up on the back end in that order. Here's what I have on the front end:

$scope.postThenPost = function() {
    $http.post('/collection', $scope.doc).success(function(data){
        for (var i = 0; i<$scope.array.length; i++) {
            var req_obj = { thing: $scope.array[i] };
            $http.post('/collection2', req_obj);
        };
    };
};

and on the back end, express runs this for posting into /collection2:

exports.create = function(req, res) {
    var q = new q(req.body.thing);
    q.save(function(err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(q);
        };
    });
};

Is there something I can do to ensure that the array goes in to the database in order? Thanks in advance

1
  • 2
    The $http.post is asynchonous by default. I recommend you posting the entire $scope.array to /collection2, then loop through the array on back end. Commented Jul 10, 2015 at 3:42

1 Answer 1

1

It's wasteful sending $scope.array.length number of HTTP requests when you have all the data you want to send ready.

Just post the whole array to your backend and then you can save them in a loop on the backend using something like async to guarantee the order.

Sign up to request clarification or add additional context in comments.

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.