So i was trying to retrive a document from mongodb but then this error came up i dont know if its database error or code error so any help?
Encountered error on event listener "guildMemberAdd" for event "guildMemberAdd" at path "D:\Project\Troll Kick Bot\bin\listeners\guildMemberAdd.js" TypeError: Cannot read properties of null (reading '_id')
at GuildMemberAddListener.<anonymous> (D:\Project\Troll Kick Bot\bin\listeners\guildMemberAdd.js:34:36)
at Generator.next (<anonymous>)
at fulfilled (D:\Project\Troll Kick Bot\bin\listeners\guildMemberAdd.js:9:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
guildMemberAdd.ts
import { Command } from "@sapphire/framework";
import { Message } from "discord.js";
import mongoose from "mongoose";
import { victim } from "../schema/victim";
export class Victim extends Command {
public constructor(context: Command.Context, options: Command.Options) {
super(context, {
...options,
name: 'victim',
description: 'kicks the victim without mercy'
})
};
public async messageRun(message: Message) {
await mongoose.connect(process.env.Mongoose!);
const victimUser = message.mentions.members!.first();
const find = await victim.findOne({ _id: victimUser?.id});
if (find) {
return message.reply('brother that guy is already in our hitlist')
};
try {
await new victim({
_id: victimUser?.id,
guildId: message.guild?.id
}).save();
} catch(e) {
console.error(e)
} finally {
mongoose.connection.close()
}
}
}
CodePudding user response:
it looks like at this line of code await victim.findOne({ _id: victimUser?.id});
the victimUser?.id
is giving you a null
value. Mongoose then seems to panic saying that - you are asking me to find a document whose _id
is null. Therefore the error is more of - why did you get a null
for victimUser?.id. Check if thedata passed into function messageRun
has that field id
in first place.