You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Sequelize中统计特定值行数并自定义结果键名?

问题

我有一个MySQL表,在Node.js中使用Sequelize进行查询。现有代码可正确统计type为fresh的各title行数,输出结果为[{title:17}, {title:15}],但希望修改代码得到[{orange:17}, {apple:15}]形式的结果,该如何调整?

现有代码如下:

const data = await db.models.fruits.findAll({
    where: { type: `fresh` },
    group: `title`,
    attributes: [`title`, [Sequelize.fn(`COUNT`, `title`), `title`]]
})

const rows = data.map(el => el.get({ plain: true }))
console.log(rows)
解决方案

要输出目标格式,只需要调整查询配置和数据转换逻辑,以下两种方法都可以实现:

方法一:保留title字段构造对象

修改查询的attributes配置,给统计结果起明确别名,同时保留title字段;之后在map遍历的时候,用title作为键、统计值作为值生成新对象:

const data = await db.models.fruits.findAll({
    where: { type: `fresh` },
    group: `title`,
    // 同时获取title和统计数,给统计数起别名count
    attributes: [`title`, [Sequelize.fn(`COUNT`, `title`), `count`]]
})

// 解构出title和count,构造目标格式的对象
const rows = data.map(el => {
    const { title, count } = el.get({ plain: true });
    return { [title]: count };
})

console.log(rows)

方法二:从实例属性取title

如果不想在查询结果里保留title字段,可以只查询统计值,之后直接从模型实例的title属性取值构造对象:

const data = await db.models.fruits.findAll({
    where: { type: `fresh` },
    group: `title`,
    // 只查询统计数,起别名count
    attributes: [[Sequelize.fn(`COUNT`, `title`), `count`]]
})

// 从实例的title属性获取键名,搭配统计值构造对象
const rows = data.map(el => {
    const { count } = el.get({ plain: true });
    return { [el.title]: count };
})

console.log(rows)

两种方法都能得到你想要的输出格式,推荐第一种,逻辑更清晰,避免直接操作模型实例属性的潜在问题。

内容的提问来源于stack exchange,提问作者Nastro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 09:52:14