Home > Software engineering >  MongoDB findOne() Cannot read property of null
MongoDB findOne() Cannot read property of null

Time:04-01

I'm trying to create a discord bot, specifically the married.

I am using a MongoDB database. There is only one problem right now, when the database is empty, I get this error

An error occurred while running the command: TypeError: Cannot read property 'userID' of null

What can be done about it? Help me please!

const { Command } = require("discord.js-commando");
const mongoose = require("mongoose");

mongoose.connect('mongodb srv://admon:[email protected]/dbname?retryWrites=true&w=majority');

//create Schema

const marrySchema = new mongoose.Schema({
    userID: {
        type: mongoose.SchemaTypes.String,
        required: true
    },

    userPartnerID: {
        type: mongoose.SchemaTypes.String,
        required: true
    }
});

const Marry = mongoose.model('Marry', marrySchema);

module.exports = class MarryCommand extends Command {
    constructor(client) {
        super(client, {
            name: "marry",
            memberName: "marry",
            group: "test",
            description: "Marry the mentioned user",
            guildOnly: true,
            args: [{
                key: "userToMarry",
                prompt: "Please select the member you wish to marry.",
                type: "member",
            }, ],
        });
    }

    async run(message, { userToMarry }) {
        const exists = await Marry.findOne({ userID: message.author.id });
        const married = await Marry.findOne({ userID: userToMarry.id });

        if (!userToMarry) {
            return message.channel.send("Please try again with a valid user.");
        }
        if (exists.userID == message.author.id) {
            return message.channel.send("You are already married!");
        }
        if (married.userID == userToMarry.id) {
            return message.channel.send("This user is already married!");
        }
        if (userToMarry.id == message.author.id) {
            return message.channel.send("You cannot marry yourself!");
        }
        if (exists.userID != message.author.id && married.userID != userToMarry.id) {
            message.channel.send(
                    `**Important announcement!**
    
    ${message.author} makes a marriage proposal ${userToMarry}
    
    Are you ready to get married?`
                )
                .then((message) => {
                    message.react("           
  • Related