如何从Sequelize的输出中删除关联?

Hyr*_*yra 1 node.js express sequelize.js

我为Model User定义了classMethod

// model user.js
classMethods: {
    associate: function(models) {
        User.belongsToMany(models.project, {through: 'user_project', foreignKey: 'user_id', otherKey: 'project_id'})
    }
}
Run Code Online (Sandbox Code Playgroud)

从Express i中的路由然后查询该用户的项目并将其输出为JSON

user.getProjects({
    attributes: ['id', 'title'],
})
.then(function(projects) {
    res.json(projects)
})
Run Code Online (Sandbox Code Playgroud)

这工作正常,除了输出还包含user_project我想隐藏/省略/删除的属性

[
  {
    "id": 8,
    "title": "Some project",
    "user_project": {
       "created_at": "2017-02-16T22:52:48.000Z",
       "updated_at": "2017-02-16T22:52:48.000Z",
       "project_id": 8,
       "user_id": 5
     }
  },
  //etc.
Run Code Online (Sandbox Code Playgroud)

我尝试了各种exclude和include语句,但输出总是包含它.

有没有办法在输出中没有这个显示?

Hyr*_*yra 6

我偶然发现了解决方案.

要从连接表中删除属性,您可以使用joinTableAttributes,如下所示:

user.getProjects({
    attributes: ['id', 'title'],
    joinTableAttributes: []
})
.then(function(projects) {
    res.json(projects)
})
Run Code Online (Sandbox Code Playgroud)

通过这样做,它将删除user_project表的(参见OP)输出,结果是:

[
  {
    "id": 8,
    "title": "Test Project",
  },
  {
    "id": 4,
    "title": "Another one",
  }
]
Run Code Online (Sandbox Code Playgroud)

  • 必须承认它很好地隐藏在sequelize文档中,只有关于`joinTableAttributes`的单句;) (2认同)