【问题标题】:Can I return fields as nested objects on Sequelize js?我可以在 Sequelize js 上将字段作为嵌套对象返回吗?
【发布时间】:2017-11-15 01:14:33
【问题描述】:

我在 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 查询中进行,或者我应该在之后解析结果吗?

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

    您可以在返回之前更改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);
    

    【讨论】:

    • 您需要迭代对象数组。问题已更新。
    猜你喜欢
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    相关资源
    最近更新 更多