I’m having this issue where I’m trying to create a leveling system in Discord using discord.js and MongoDB. Every time I try to upload my data to the database, I keep getting the error message
db.Collection is not a constructor
I’ve followed the instructions from How do I save a new data to MongoDB? post on saving new data to MongoDB, but I’m still getting the same error.
Here is my code that I’ve been working on:
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.findOne(query).then(async (level) => {
if (!level) {
const newLevel = new level({
userId: message.author.id,
guildId: message.guild.id,
xp: XPToGive,
});
await newLevel.save();
return;
}
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;
});
});
} catch (error) {
console.error(`[ERROR] ${error}`);
}
}
I’m having trouble with using find()
instead of findOne()
in my code. It’s giving me more errors, and I really want my code to be error-free and able to save my data in the database.