【发布时间】:2019-02-01 21:38:31
【问题描述】:
目前,我正在尝试对需要插入的对象数组进行迭代,具体取决于数组中的项目数(来自 request.body)。
预期行为:
我认为 for 循环会导致不同的 sequelize SQL 查询,这些查询将一个接一个地插入到数据库中。
--
实际行为:
实际行为是只有数组中的最后一项被插入到数据库中,而第一项被覆盖而不被插入到数据库中。
--
我的问题:
如何改变这个现有的逻辑,以便能够在使用事务/sequelize SQL 查询时将多条记录插入数据库?
我发送给 API 请求的数据是:
[{
"venue_id": 5,
"event_id": 13,
"table_id": 4,
"date_in": "2017-11-30",
"date_out": "2017-12-31",
"check_in": "2017-12-31T17:04:42.333Z",
"check_out": "2017-12-31T17:05:42.333Z"
},
{
"venue_id": 6,
"event_id": 18,
"table_id": 6,
"date_in": "2017-11-30",
"date_out": "2017-12-31",
"check_in": "2017-12-31T17:04:42.333Z",
"check_out": "2017-12-31T17:05:42.333Z"
}]
API调用逻辑如下。这个 API 请求基本上做了以下事情:
- 启动 SQL 事务,以便在出现问题时提交或回滚。
- 搜索场所 ID、客户 ID 和表格 ID。 (以防有人试图插入一些不存在的 id)
- 一起计算桌子的价格
- 创建预订
- 提交事务并返回响应。
router.post(
"/api/v1/reservations",
[passport.authenticate("jwt", { session: false }), isCustomer],
(request, response) => {
return models.sequelize.transaction().then(t => {
// I was trying to do this by using a for loop but it doesn't seem to work.
for (var i = 0; i < request.body.length; i++) {
return models.Venue.findById(request.body[i].venue_id)
.then(venue => {
return models.Customer.findById(request.customer.id);
})
.then(customer => {
return models.Table.findAllById(request.body[i].table_id);
})
.then(tables => {
var price = 0;
for (var i = 0; i < tables.length; i++) {
price = price + tables[i].price;
}
return models.Reservation.createReservation(
request.body[i],
price,
request.customer.id
).then(reservation => {
return reservation.addTables(tables).then(() => {
if (request.body.length - 1 === i) {
t.commit().then(() => {
return response.status(200).send(reservation);
});
}
});
});
})
.catch(error => {
console.log(error);
t.rollback().then(() => {
return response.status(error.status_code).send(error.message);
});
});
}
});
}
【问题讨论】:
标签: node.js promise sequelize.js