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

使用Mongoose遍历MongoDB集合文档 为Discord Embed添加字段

错误根因

你遇到的报错是因为setTimestamp/setFooter都是Discord.js的MessageEmbed实例专属方法,但你直接把这类方法链式调用在了items.find().then()的返回值上,而then()返回的是Promise对象,自然不存在Embed相关方法,才会抛出类型错误。

正确实现方案

推荐搭配你函数已经使用的async关键字,用await写法避免回调嵌套,逻辑更清晰:

修正后的store命令代码

module.exports = {
    name: `store`,
    aliases:['shop'],

    /**
     * @param {Client} client
     * @param {Message} message
     * @param {String[]} args
     */
    run: async(client, message, args) => {
        const exampleEmbed = new Discord.MessageEmbed()
            .setColor('#0099ff')
            .setTitle('Boblox Shop')
            .setDescription('Buy stuff with $buy <id>')
        const items = require('./shop')

        try {
            // 等待数据库查询返回集合内所有文档
            const documents = await items.find({})
            // 遍历所有文档为Embed添加对应字段
            documents.forEach(u => {
                // 你也可以按需求拼接库存、稀有度等其他Schema字段
                exampleEmbed.addField(`${u.ItemName}`, `Price: ${u.Price}`)
            })
            // 所有字段添加完成后再配置Embed的其他属性
            exampleEmbed.setTimestamp()
            // 发送构造完成的Embed
            await message.channel.send({ embeds: [exampleEmbed] })
        } catch (err) {
            console.error('商店加载失败:', err)
            await message.reply('商店暂时无法访问,请稍后重试')
        }
    }
}

如果你坚持使用.then()写法,需要把所有Embed操作、发送逻辑都放到then的回调内部,不要链式接在then()后面:

items.find({}).then(function(documents) {
    documents.forEach(function(u) {
        exampleEmbed.addField(`${u.ItemName}`, `Price: ${u.Price}`)
    })
    exampleEmbed.setTimestamp()
    message.channel.send({ embeds: [exampleEmbed] })
}).catch(err => {
    console.error(err)
    message.reply('商店加载失败')
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:36:02