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

如何在Discord Embed中循环展示多个Mongoose文档

解决Discord Bot中在Embed展示所有Mongoose文档的问题

你的核心问题是未遍历查询到的所有Mongoose文档,且嵌套的then导致逻辑复杂难以扩展。以下是优化后的实现思路和代码:

关键优化点

  • 减少重复数据库查询:无需调用countDocuments,直接通过find结果的length获取记录数量
  • 用async/await替代嵌套then,让代码逻辑更清晰易读
  • 循环遍历所有查询到的文档,动态向Embed添加对应字段

修改后的完整代码

const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');

const tiny = require("tiny-json-http");
const date = require('date-and-time');

const Calls = require('../calls.js');
const mongoose = require("mongoose");
mongoose.connect('mongodb+srv://*****:*******@*******.ilnqf.mongodb.net/*******?retryWrites=true&w=majority');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('open')
        .setDescription('CHECK YOUR OPEN POSITIONS'),
    async execute(interaction) {
        try {
            // 一次查询获取用户所有未平仓记录
            const openPositions = await Calls.find({ 
                userID: interaction.user.id, 
                closeTime: '' 
            });
            const count = openPositions.length;

            const embed = new EmbedBuilder()
                .setColor(0x674EA7)
                .setTimestamp(Date.now());

            if (count === 0) {
                embed.setDescription(`<@${interaction.user.id}>, has no open position.`);
            } else {
                // 处理描述中的单复数
                embed.setDescription(`<@${interaction.user.id}>, has a total of __${count} open position${count !== 1 ? 's' : ''}__.`);
                
                // 循环遍历所有记录,逐个添加字段
                openPositions.forEach(position => {
                    embed.addFields(
                        { name: '**TOKEN**', value: position.coin, inline: true },
                        { name: '**POSITION**', value: position.callType, inline: true }
                    );
                });
            }

            await interaction.reply({ embeds: [embed] });
        } catch (error) {
            console.error(error);
            await interaction.reply({ content: '查询开仓记录时发生错误', ephemeral: true });
        }
    },
};

代码说明

  1. 合并查询操作:仅通过一次find请求获取所有符合条件的记录,用结果数组的length替代单独的计数查询,提升性能
  2. 动态字段生成:通过forEach循环遍历所有文档,为每个记录添加对应的TOKEN和POSITION字段,自动以inline方式并排展示
  3. 简化分支逻辑:合并了count为1和count>1的处理逻辑,用模板字符串自动处理单复数描述,减少冗余代码
  4. 优化错误反馈:除了控制台打印错误,还向用户返回了友好的错误提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:22:25