【发布时间】:2015-07-10 11:48:26
【问题描述】:
我正在尝试使用 node.js express 和 mongoose(MEAN 堆栈)在 MongoDB 中保存一组对象。但是,当我在前端为数组中的每个项目发出 http 发布请求时,它们不会按该顺序显示在后端。这是我在前端的内容:
$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);
};
};
};
在后端,express 运行这个以发布到 /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);
};
});
};
我可以做些什么来确保数组按顺序进入数据库吗?提前致谢
【问题讨论】:
-
$http.post 默认是异步的。我建议您将整个
$scope.array发布到/collection2,然后在后端循环遍历数组。
标签: javascript node.js mongodb loops mongoose