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

MongoDB中Discord机器人物品使用功能实现:增减与删除

Discord机器人物品使用系统实现

针对你的需求,以下是实现物品使用系统的完整方案,逻辑和你现有购买系统保持一致:

核心逻辑

当用户使用物品时:

  • 若物品数量为1,直接从库存中移除该物品
  • 若物品数量大于1,将数量减1

完整实现代码

const { Client, Message, MessageEmbed } = require('discord.js');
const { User } = require("../../databasing/schemas/User")
const inventory = require('../../databasing/schemas/inventory')
const items = require('../../items/shopItems')

module.exports = {
    name: 'use',
    /** 
     * @param {Client} client 
     * @param {Message} message 
     * @param {String[]} args 
     */
    run: async(client, message, args) => {
        const itemToUse = args[0]?.toLowerCase();
        const embed = new MessageEmbed({ color: "#2F3136" });

        // 检查输入是否为空
        if(!itemToUse) return message.channel.send({
            embeds: [embed.setTitle('<:redCross:1004290018724020224> | 请指定要使用的物品!')]
        });

        // 检查物品是否存在于商店列表
        const validItem = items.find(val => val.item.toLowerCase() === itemToUse);
        if(!validItem) return message.channel.send({
            embeds: [embed.setTitle(`<:redCross:1004290018724020224> | ${itemToUse} 不是有效的物品!`)]
        });

        const param = { User: message.author.id };
        const inventoryData = await inventory.findOne(param);

        // 检查用户是否有库存记录或该物品
        if(!inventoryData || !inventoryData.Inventory[itemToUse]) {
            return message.channel.send({
                embeds: [embed.setTitle(`<:redCross:1004290018724020224> | 你的库存中没有 ${itemToUse}!`)]
            });
        }

        // 处理物品使用逻辑
        const itemCount = inventoryData.Inventory[itemToUse];
        if(itemCount === 1) {
            // 数量为1时移除物品
            delete inventoryData.Inventory[itemToUse];
        } else {
            // 数量大于1时减1
            inventoryData.Inventory[itemToUse]--;
        }

        // 保存更新后的库存
        await inventory.findOneAndUpdate(param, inventoryData);

        // 发送成功提示
        message.channel.send({
            embeds: [embed.setTitle(`<:greenTick:1004290019927785472> | 成功使用 ${itemToUse}!剩余数量:${inventoryData.Inventory[itemToUse] || '已移除'}`)]
        });
    }
}

关键代码解释

  1. 物品有效性验证:通过items.find检查输入的物品是否在商店物品列表中,避免无效物品操作。
  2. 库存检查:先获取用户的库存文档,判断是否存在该物品。
  3. 数量处理逻辑:
    • 当数量等于1时,使用delete操作符从Inventory对象中移除该物品键
    • 当数量大于1时,直接对数值做减1操作
  4. 数据库更新:使用findOneAndUpdate保存修改后的库存数据,确保数据持久化。

注意事项

  • 确保你的inventory schema中Inventory字段定义为Object类型,支持键值对存储(如{ pizza: 5 })
  • 可以根据需求扩展物品使用的额外效果(比如使用披萨增加用户体力等),在库存更新后添加对应逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 11:57:09