输出对象与关联数据?

时间:2016-06-26 20:00:30

标签: node.js sequelize.js

user是一个具有许多属性的Sequelize实例。是否有任何简写输出用户的属性?像这样:

user.getUserAttributes().then((attributes)=> {
    res.json({
        user: user,
        attributes: attributes
    });
});

1 个答案:

答案 0 :(得分:0)

您可以输出属性名称数组,如下所示:

res.json({
    user: user,
    attributes: Object.keys(user.get({
      plain : true
    }))
});

假设用户实例如下所示:

var user = {
  firstName : "John",
  lastName : "Doe",
  sequelizeInstanceAttribute1 : "bla",
  sequelizeInstanceAttribute2 : [1, 2, 3],
  ...
};

然后JSON响应如下所示:

{
  user: {
    firstName : "John",
    lastName : "Doe"
  },
  attributes : [
    'firstName',
    'lastName'
  ]
}