Discord JS 如何遍历字符串化JSON处理Sequelize用户卡集并发送embed
问题修正指南
你遇到的两个核心问题都是新手开发JS时很容易踩的基础坑,逐点拆解:
- 第一,你写的
const JSONcardlist = console.log(...)这行是错误的。console.log本身没有返回值,不管你在括号里打印什么内容,执行完永远返回undefined——这就是你后续引用JSONcardlist时永远拿不到值的直接原因。打印日志是执行副作用,不要把console.log的返回值当业务结果存进变量。 - 第二,你之前想遍历序列化后的JSON字符串报“不可迭代”的错误,是因为搞错了Sequelize查询结果的结构。
UserCollec.findAll()返回的cards本身就是可迭代的模型实例数组,根本不需要先JSON.stringify转成字符串再处理。JSON.stringify的输出是纯文本字符串,不是数组结构,自然没法循环取出每个卡片的字段值。
正确实现逻辑
- 把调试日志和业务逻辑拆开,打印的内容不影响实际要发送的消息内容
- 直接遍历原生的查询结果数组,把每个卡片的字段拼成Embed支持的纯文本
- 处理空卡集的边界情况,避免用户无收藏时消息显示异常
修正后的参考代码
} else if (command === 'Collection' || command === 'collec' || command === 'col') { const target = message.author.id; // 查询卡集,拿到可迭代的模型实例数组 const cards = await UserCollec.findAll({ where: {user_id: target}, attributes: ['card_name', 'card_lvl', 'amount'] }); // 调试日志正常写,不要把返回值赋值给业务变量 console.log(`${message.author} 的卡集查询结果:`, cards); // 直接遍历原生数组拼Embed需要的文本 let cardListText; if (cards.length === 0) { cardListText = "你还没有收集到任何卡片哦"; } else { cardListText = cards.map(card => `**${card.card_name}** | 等级:${card.card_lvl} | 持有数量:${card.amount}` ).join('\n'); } // 构建Discord富文本组件 const collectionEmbed = new EmbedBuilder() .setTitle("我的卡集") .setDescription(cardListText) .setColor("Blurple"); // 私信发送给用户 await message.author.send({embeds: [collectionEmbed]}); }
轻量化小技巧
如果觉得从Sequelize模型实例上读字段比较麻烦,可以在查询参数里加raw: true,返回结果会直接是纯JS对象数组,不需要额外解包模型:
const cards = await UserCollec.findAll({ where: {user_id: target}, attributes: ['card_name', 'card_lvl', 'amount'], raw: true });
内容的提问来源于stack exchange,提问作者Beetlejuice
相关产品推荐
相关产品推荐

