我在 sequelize.js 中有以下查询:
getBookingById: (req, res) => {
models.booking.findAll({
where: {
id: { $in: [1, 2, 3] },
},
include: [{
model: models.cust,
attributes: ['name', 'id'],
}],
attributes: [['id', 'bookingId'], 'propertyKey', 'propertyId'] })
.then((result) => {
if (!result) return res.status(204);
return res.status(200).json(result);
}).catch(err => res.status(500);
};
我的回复如下:
[{
"bookingId": 1,
"propertyKey": "ABC",
"propertyId": "123",
"cust": {
"name": "David David",
"id": 8
}
},
{
"bookingId": 2,
"propertyKey": "ABC",
"propertyId": "123",
"cust": {
"name": "David David",
"id": 8
}
}]
我想将 propertyKey
和 propertyId
字段作为嵌套对象返回:
"property": {
"propertyKey": "ABC",
"propertyId": "123",
}
是否可以在 Sequelize 查询中执行此操作,或者我应该在之后解析结果吗?
最佳答案
您可以在返回之前更改 result
变量。
.then((result) => {
if (!result) return res.status(204);
for (var i = 0; i < result.length ; i++){
result[i].property = {
"propertyKey" : result.propertyKey ,
"propertyId": result.propertyId
}
delete result[i].propertyKey;
delete result[i].propertyId;
}
return res.status(200).json(result);
}).catch(err => res.status(500);
关于javascript - 我可以在 Sequelize js 上将字段作为嵌套对象返回吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47288984/