node.js - Sequelize : Return associated results array without embedded objects

标签 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 方法来以这种方式格式化数据?

最佳答案

通过将查询更改为:

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',
});

关于node.js - Sequelize : Return associated results array without embedded objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56384079/

相关文章:

javascript - 使用 NodeJS 从 HTML 中提取字符串

node.js - 如何防止可传递的开发依赖被收缩包装

javascript - Javascript中隐藏信息会牺牲性能吗?

mysql - Docker Compose 连接 ECONNREFUSED 172.18.0.4 :3306

postgresql - 如何在带有 where 子句的 sequelize 中使用嵌套包含?

node.js - 咕噜声 : Livereload doesn't work

javascript - 如何使用 Node.js 解析 JSON?

mysql - Node.js v10.20.1::> Sequelize findOne 速度太慢

node.js - 使用 sequelize 检索链接状态字段的值

graphql - 如何使用 GraphQL 突变在解析器中添加递归逻辑?