我有一種情況,我需要利用完整的Sequelize實例,但只想返回instance.dataValues
,所以我遍歷鍵(遞歸如果需要)將其轉換爲原始值。我沒有真正運行下面的代碼,因此它可能包含一些錯誤
const extend = require('util')._extend;
function getDataValues(obj) {
// create a copy of the dataValues
const compact = extend({}, (obj && obj.dataValues) || obj);
// loop over the keys
Object.keys(compact).forEach(key => {
const field = compact[key];
// it's an Array of Models
if (field instanceof Array) {
compact[key] = field.map(include =>
getDataValues(include)
);
}
// it's a single Model
if (field.dataValues) {
compact[key] = extend({}, field.dataValues);
}
// otherwise it was a "string" or "int" or other simple value
});
// resolve the compacted dataValues
return Promise.resolve(compact);
}
Model.findById(id, {
include: [{
model: Model2,
as: "model_twos"
}],
})
.then(model => getDataValues(model))
.then(compact => console.log(util.inspect(compact)));