Home > database >  Error when trying to increment a database value by 1. MongoDB
Error when trying to increment a database value by 1. MongoDB

Time:10-21

I am creating a warn command for my discord bot using discord.js v14 and the latest mongoose version. For my warn command, I want it to have a number value that starts at 1; when the same user is warned again, the number value goes up to 2. But I am receiving an error when the command is ran.

CODE:

const { Client, SlashCommandBuilder, PermissionFlagBits, EmbedBuilder, PermissionFlagsBits } = require("discord.js");
const ms = require("ms");
const Schema = require("../../Models/Warn");


module.exports = {
    data: new SlashCommandBuilder()
        .setName("warn")
        .setDescription("Warns a member in your guild. **ADMIN**")
        .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
        .addUserOption(option => 
            option.setName("target")
                .setDescription("Select the user you wish to warn.")
                .setRequired(true)
        )
        .addStringOption(option =>
            option.setName("reason")
                .setDescription("What is the reason of the warn?")
        ),

    async execute(interaction) {
        const { guild, options } = interaction

        const user = options.getUser("target")
        const member = guild.members.cache.get(user.id);
        const reason = options.getString("reason") || "No reason provided";

        const errEmbed = new EmbedBuilder()
            .setDescription('Something went wrong. Please try again later.')
            .setColor(0xc72c3b)

        const successEmbed = new EmbedBuilder()
            .setTitle("**:white_check_mark: Warned**")
            .setDescription(`Succesfully warned ${user}.`)
            .addFields(
                { name: "Reason", value: `${reason}`, inline: true }
            )
            .setColor(0x5fb041)
            .setTimestamp();

        if (member.roles.highest.position >= interaction.member.roles.highest.position)
                return interaction.reply({ embeds: [errEmbed], ephemeral: true });
            
        if(!interaction.guild.members.me.permissions.has(PermissionFlagsBits.ModerateMembers))
                return interaction.reply({ embeds: [errEmbed], ephemeral: true });


        try {
            let ts = Date.now();

            let date_ob = new Date(ts);
            let date = date_ob.getDate();
            let month = date_ob.getMonth()   1;
            let year = date_ob.getFullYear();

            actualDate = year   "-"   month   "-"   date;
            var dbStuff = new Schema({ userId: member.id, reason: reason, Date: actualDate, staffId: interaction.member.name, number: { $inc: 1 }});

            dbStuff.save(function (err, DB) {
                if(err) return console.error(err);
                console.log("New user has been warned. Saved to database.")
            })

            interaction.reply({ embeds: [successEmbed], ephemeral: true });
            //await guild.channels.cache.get('1031302408934015016').send(`${interaction.member.name} has muted ${user} for the time ${time} for the reason ${reason}`)
        } catch (err) {
            console.log(err);
        }
    }
}

ERROR:

Error: Warn validation failed: number: Cast to string failed for value "{ '$inc': 1 }" (type Object) at path "number"
    at ValidationError.inspect (C:\Users\Robin\Documents\Multi-Purpose Bot\node_modules\mongoose\lib\error\validation.js:49:26)
    at formatValue (node:internal/util/inspect:782:19)
    at inspect (node:internal/util/inspect:347:10)
    at formatWithOptionsInternal (node:internal/util/inspect:2167:40)
    at formatWithOptions (node:internal/util/inspect:2029:10)
    at console.value (node:internal/console/constructor:332:14)
    at console.warn (node:internal/console/constructor:365:61)
    at C:\Users\Robin\Documents\Multi-Purpose Bot\Commands\Moderation\warn.js:60:40
    at C:\Users\Robin\Documents\Multi-Purpose Bot\node_modules\mongoose\lib\model.js:5195:18
    at processTicksAndRejections (node:internal/process/task_queues:78:11) {
  errors: {
    number: CastError: Cast to string failed for value "{ '$inc': 1 }" (type Object) at path "number"
        at SchemaString.cast (C:\Users\Robin\Documents\Multi-Purpose Bot\node_modules\mongoose\lib\schema\string.js:603:11)
        at SchemaString.SchemaType.applySetters (C:\Users\Robin\Documents\Multi-Purpose Bot\node_modules\mongoose\lib\schematype.js:1201:12)
        at model.$set (C:\Users\Robin\Documents\Multi-Purpose Bot\node_modules\mongoose\lib\document.js:1368:22)
        at model.$set (C:\Users\Robin\Documents\Multi-Purpose Bot\node_modules\mongoose\lib\document.js:1093:16)
        at model.Document (C:\Users\Robin\Documents\Multi-Purpose Bot\node_modules\mongoose\lib\document.js:166:12)
        at model.Model (C:\Users\Robin\Documents\Multi-Purpose Bot\node_modules\mongoose\lib\model.js:121:12)
        at new model (C:\Users\Robin\Documents\Multi-Purpose Bot\node_modules\mongoose\lib\model.js:5020:15)
        at Object.execute (C:\Users\Robin\Documents\Multi-Purpose Bot\Commands\Moderation\warn.js:57:27)
        at Object.execute (C:\Users\Robin\Documents\Multi-Purpose Bot\Events\interactions\interactionCreate.js:12:21)
        at Client.<anonymous> (C:\Users\Robin\Documents\Multi-Purpose Bot\Handlers\eventHandler.js:25:63) {
      stringValue: `"{ '$inc': 1 }"`,
      messageFormat: undefined,
      kind: 'string',
      value: [Object],
      path: 'number',
      reason: null,
      valueType: 'Object'
    }
  },
  _message: 'Warn validation failed'
}

CodePudding user response:

You are passing $inc inside the function that creates the new document.

$inc is an update operator. So you can not use it during the creation of the document.

Since you are just creating new document, consider setting the value of number property directly to 0 or 1:

new Schema({ 
  userId: member.id, 
  reason: reason, 
  Date: actualDate, 
  staffId: interaction.member.name, 
  number: 1
});
  • Related