【问题标题】:Print a sequalize object (with sub dependent object)打印一个 sequelize 对象(带有子依赖对象)
【发布时间】:2017-04-30 22:14:56
【问题描述】:
我运行一个查询(假设是一个 User 表,以及它所有对应的 UserPhone 条目,这些条目都有一个 userId 作为外键,这样一个用户就有很多电话)。
我想将结果打印到控制台。
JSON.stringify 仅用于打印用户,但不能打印用户电话,尽管它们存在于 sequelize 响应对象中
如果我改用util.inspect,我会得到一切,但也会有很多噪音,例如$options 和续集对象的许多其他属性。
我不想用{raw: true} 更改我的查询,只是想打印结果。
【问题讨论】:
标签:
json
node.js
sequelize.js
stringify
【解决方案1】:
我有一种情况,我需要使用完整的 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)));