I’m new to databases and I’m currently working on a Discord bot project. I followed a YouTube tutorial and decided to use MongoDB. However, when I tried to send data for a level system to the database using the save()
method, I encountered the following error:
TypeError: level.save is not a function
messageCreate.js:
const { Events, Message } = require("discord.js");
const Level = require("../models/Level");
const getLevelXP = require("../utility/getLevelXP");
function getRandomXP(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
module.exports = {
name: Events.MessageCreate,
async execute(message) {
if (!message.inGuild() || message.author.bot) return;
const XPToGive = getRandomXP(5, 15);
const query = {
userId: message.author.id,
guildId: message.guild.id,
};
try {
const level = await Level.find(query);
if (level) {
level.xp += XPToGive;
if (level.xp > getLevelXP(level.level)) {
level.xp = 0;
level.level += 1;
message.channel.send(
`@${message.member} have been leveled up to **Level ${level.level}**`,
);
}
await level.save().catch((error) => {
console.error(`[ERROR] ${error}`);
return;
});
} else {
const newLevel = new level({
userId: message.author.id,
guildId: message.guild.id,
xp: XPToGive,
});
await newLevel.save();
}
} catch (error) {
console.error(`[ERROR] ${error}`);
}
},
};
Level.js:
const { Schema, model } = require("mongoose");
const levelSchema = new Schema({
userId: {
type: String,
required: true,
},
guildId: {
type: String,
required: true,
},
xp: {
type: Number,
default: 0,
},
level: {
type: Number,
default: 0,
},
});
module.exports = model("Level", levelSchema);
After that error, I double-checked and found that no data had been uploaded to the database. My expectation is to make the data that I’m trying to save, is sent to the database.