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

时间:2017-11-14 15:04:00

标签: javascript node.js sequelize.js

我在 sequelize.js

中有以下查询
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="team.css">
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
    <img src="Static shots/Mathew-Demo.png" id="imgAnimate">

    <script src="team.js" type="text/javascript">
</body>

我的回答如下:

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

是否可以在sequelize查询中执行此操作,或者我应该在之后解析结果吗?

1 个答案:

答案 0 :(得分:0)

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