Abel
Abel

Reputation: 51

How to increase values in Mongo DB

I want to increase the current number in the database.

Example: If the number in the database is 0 I want it to increase by 1 every time I use the PostImage command.

The Error: When I console.log(debug) It gives undefined

const attachment = await interaction.options.getAttachment("input");
            const caption = await interaction.options.getString("caption");
            const channel = client.channels.cache.get("988214204660064286");

            const embed = new MessageEmbed()
                .setAuthor({ name: `${username} Posted`, iconURL: `${profilePicData}` })
                .setColor("#303236")
                .setDescription(`${caption}`)
                .setImage(`${attachment.url}`)
                .setFooter({ text: `user ID: ${userId}`, iconURL: `${profilePicData}` })
            channel.send({ embeds: [embed] }).then(async (msg) => {
                await msg.react("πŸ‘Ž");
                await msg.react("πŸ‘");
            });

            db.findOneAndUpdate({
                UserId: userId,
                PostAmount: 1
            })
            const dubug = data.map((x) => `${x.PostAmount}`).join('\n');
            console.log(dubug)

Upvotes: 0

Views: 256

Answers (2)

エース
エース

Reputation: 57

Increasing a data on mongoose uses {$inc: {your_data}}

db.findOneAndUpdate({
    UserId: userId,
    PostAmount: 1 //You can now remove these one.
}, {$inc: {PostAmount: +1}}, async(err, data) => {
   if(data) {
      data.PostAmount += 1;
      await data.save();
   }
})

You should remove these code line PostAmount: 1 because UserId Will find its own data on database.

Upvotes: 2

Teyrox
Teyrox

Reputation: 192

To increase the value of PostAmount by 1, you can simply get the document, change the value of PostAmount to PostAmount + 1 and save the document

let doc = await db.findOne({ UserId: userId });
doc.PostAmount = doc.PostAmount + 1;
await doc.save();

Besides that, debug returns undefined because it is not defined. It is probably because in the debug definition it tries to map data which I don't see defined either.

Upvotes: 0

Related Questions