2017-11-14 5 views
1

私は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クエリ内で実行することはできますか。後の結果を解析しますか?

答えて

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); 
+0

オブジェクトの配列を反復処理する必要があります。質問が更新されました。 – wizard

+0

配列で更新された回答 –

関連する問題