mongoose 尝试将数据库值增加1时出错,MongoDB

kmbjn2e3  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(103)

我使用discord.jsv14和最新的mongoose版本为discord bot创建了一个warn命令。当同一用户再次收到警告时,数值将上升到2。但是在运行该命令时,我收到了错误。
代码:

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: 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'
}
oprakyz7

oprakyz71#

在创建新文档的函数内部传递$inc
$inc是一个更新运算符,所以在创建文档时不能使用它。
由于您只是在创建新文档,请考虑将number属性得值直接设置为01

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

相关问题