序列化:返回没有嵌入式对象的关联结果数组

时间:2019-05-30 18:54:19

标签: node.js sequelize.js

使用此查询:

const noteRecords = await db.job_notes.findAll({
  attributes: [],
  include: [
    {
      model: db.jobs,
      attributes: [],
      where: {
        id: jobId,
      },
    },
    {
      model: db.notes,
      attributes: ['id', 'body'],
    },
  ],
});

Sequelize返回结果为:

[
   {
      "note": {
         "id": "2",
         "body": "Lorem Ipsume Dolor Sumut"
      }
   },
   {
      "note": {
         "id": "3",
         "body": "Sum es est sumus estis sunt"
      }
   }
]

我希望它返回为:

[
  {
     "id": "2",
     "body": "Lorem Ipsume Dolor Sumut"
  }, 
  {
     "id": "3",
     "body": "Sum es est sumus estis sunt"
  }
]

除了noteRecords = noteRecords.map(note => note.note)以外,还有一种Sequelize方法来以这种方式格式化数据吗?

1 个答案:

答案 0 :(得分:0)

通过将查询更改为:

const noteRecords = await db.notes.findAll({
  include: [
    {
      model: db.jobs,
      attributes: [],
      where: {
        id: jobId,
      },
    },
  ],
});

由于我在db.notes中的关联是:

models.notes.belongsToMany(models.jobs, {
  through: 'job_notes',
  foreignKey: 'note_id',
  sourceKey: 'id',
});