MongoDB findOne() 无法读取 属性 of null

MongoDB findOne() Cannot read property of null

我正在尝试创建一个不和谐的机器人,特别是已婚机器人。

我正在使用 MongoDB 数据库。现在只有一个问题,当数据库为空时,我得到这个错误

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

有什么办法吗?请帮助我!

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

mongoose.connect('mongo_connection_url_here');

//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("")
                    .then(() => message.react(""))
                    .catch(() => {
                        //code
                    });
                    message.awaitReactions((reaction, user) =>
                        user.id == userToMarry.id && (reaction.emoji.name == "" || reaction.emoji.name == ""), {
                            max: 1,
                            time: 10000,
                            errors: ["time"]
                        }
                    ).then((collected) => {
                        const reaction = collected.first();
                        if (reaction.emoji.name === "") {
                            return message.channel.send("I think **no**...");
                        }
                        if (reaction.emoji.name === "") {
                                const createdExists = new Marry({
                                    userID: message.author.id,
                                    userPartnerID: userToMarry.id
                                });
                                createdExists.save().catch(e => console.log(e));

                                const createdMarried = new Marry({
                                    userID: userToMarry.id,
                                    userPartnerID: message.author.id
                                });
                                createdMarried.save().catch(e => console.log(e));

                            message.channel.send(`${message.author} and ${userToMarry} now married!!`)
                                .catch(() => {
                                    message.reply(
                                        "No reaction after 10 seconds, operation canceled"
                                    );
                                });
                        }
                    }).catch(() => {});
                }).catch(() => {});
        }
    }
};

很明显你是在没有数据的情况下从existmarried变量中取userID的key

我更喜欢使用可选链接,即 exist?.userIdmarried?.userId