javascript - 我可以在 Sequelize js 上将字段作为嵌套对象返回吗?

标签 javascript node.js sequelize.js

我在 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
   }
}]

我想将 propertyKeypropertyId 字段作为嵌套对象返回:

"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/

相关文章:

javascript - 实时 Javascript 事件跟踪(Javascript 统计)

javascript - 重新定位 jquery 验证插件上的错误消息

node.js - 为什么我使用 Sequelize 有两倍的外键

node.js - 尝试定义模型时,NodeJS Sequelize 抛出错误

node.js - Sequelize manytomany 关系不会创建关系

json - Sequelize - 不要用 JSON 响应返回密码

javascript - 我只需要构建一个像这样的散点图?我尝试过使用 Google 图表,但找不到合适的图表

javascript - jquery.upvote.js 仅适用于第一行

node.js - 无法解析模块 `perf_hooks`

python - 如何使用pymongo在mongodb中创建索引