Sequelize 查询显示多对多关系中的附加数据

Sequelize query shows additional data in Many to Many relationship

我有这个设置,用户和主题之间的多对多关系:

User.belongsToMany(Topic, {through: "UserTopics", timestamps: false});
Topic.belongsToMany(User, {through: "UserTopics", timestamps: false});

我尝试获取所有用户及其主题,这个查询做得很好:

User.findAll({
    attributes: { exclude: ["password"] },
    include: [
      { model: Topic, attributes: ['id', 'name',] }
    ]
  })

这是它的输出:

[
    {
        "id": 1,
        "firstName": "John",
        "lastName": "Doe",
        "CNP": "123",
        "email": "john@gmail.com",
        "validated": false,
        "createdAt": "2021-02-15T21:46:52.000Z",
        "updatedAt": "2021-02-15T21:46:52.000Z",
        "topics": [
            {
                "id": 1,
                "name": "crypto",
                "UserTopics": {
                    "userId": 1,
                    "topicId": 1
                }
            },
         ...
     },
     ...
]

但我遇到的问题是,我无法理解为什么会发生这种情况,那就是 UserTopics 属性会针对用户拥有的每个主题显示。

我该如何摆脱它?

读这个https://sequelize.org/master/manual/advanced-many-to-many.html

如果您想从结果中排除关联字段:

User.findAll({
    attributes: { exclude: ["password"] },
    include: [
      { model: Topic, attributes: ['id', 'name',] }
    ],
    through: {
      attributes: []
    }
})

感谢 fatur 指出该页面。 执行此操作的实际方法与他写的略有不同。 “through”属性必须在数组对象内部,像这样:

User.findAll({
    attributes: { exclude: ["password"] },
    include: [
        {
            model: Topic,
            attributes: ["id", "name"],
            through: {
                attributes: []
            }
        }
    ]
})