For my discord bot, I've implemented a purchasing system that adds items to the inventory array in mongoDB like this:
data.Inventory[itemTobuy] ++;
The stored format looks like this:
pizza: 1
I also have a system in place where users can use items from their inventory. I want to remove the item entirely if there's only one instance of it, but if there are multiple instances, I want to decrement the value by one, for example, from pizza: 5
to pizza: 4
. Although, I'm only about 25% sure on how to accomplish this.
The following is the full code for the command that adds the item if necessary:
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: 'buy',
/**
* @param {Client} client
* @param {Message} message
* @param {String[]} args
*/
run: async(client, message, args) => {
userData = await User.findOne({ id: message.author.id }) || new User({ id: message.author.id })
const itemTobuy = args[0].toLowerCase()
embed = new MessageEmbed({ color: "#2F3136" })
if(!args[0]) return message.channel.send({
embeds: [ embed.setTitle('<:redCross:1004290018724020224> | Please mention something to buy!')]
});
const itemid = !!items.find((val) => val.item.toLowerCase() === itemTobuy);
if(!itemid) return message.channel.send({
embeds: [ embed.setTitle(`<:redCross:1004290018724020224> | ${itemTobuy} is not a valid item!`)]
});
itemPrice = items.find((val) => val.item.toLowerCase() === itemTobuy).price;
userBalance = userData.wallet;
if(userBalance < itemPrice) return message.channel.send({
embeds: [embed.setTitle(`<:redCross:1004290018724020224> | You dont have enough money to buy this item(LOL)`)]
});
const param ={
User: message.author.id
}
inventory.findOne(param, async(err, data) => {
if(data){
const hasItem = Object.keys(data.Inventory).includes(itemTobuy);
if(!hasItem){
data.Inventory[itemTobuy] = 1;
} else {
data.Inventory[itemTobuy] ++;
}
await inventory.findOneAndUpdate(param, data);
} else {
new inventory({
User: message.author.id,
Inventory: {
[itemTobuy]: 1,
}
}).save()
}
message.channel.send({
embeds: [embed.setTitle(`<:greenTick:1004290019927785472> | Successfully bought ${itemTobuy}!`)]
});
userData.wallet -= itemPrice;
userData.save()
})
}
}