Home > OS >  Getting undefined when using findOne in mongoose
Getting undefined when using findOne in mongoose

Time:11-15

This is the scheme file for mongoose.

Scheme:

const mongoose = require("mongoose");
let holiday = new mongoose.Schema({
    staff: String,
    reason: String,
    expected: Number
})

module.exports = mongoose.model("holiday", holiday);

This is the main file where I was trying to fetch data but not working.

Event:

client.on('message', async message => {
    let p = config.bot.prefix;
    let client = message.client;
    if (message.author.bot) return;
    if (message.channel.type === 'dm') return;
    if (!message.content.startsWith(p)) {
        console.log(1)
        let guild = client.guilds.cache.get(config.server.id)
        if (!message.guild.id === "911962044985667584") return;
        let role = message.guild.roles.cache.find(role => role.name === "On holiday");
        if (!message.member.roles.cache.has("956942754502565908")) return;
        const embed = new MessageEmbed()
            .setTitle("Staff back from holiday")
            .addField("Staff: ", message.author.tag, true)
        const data = holidaydata.findOne({
            staff: message.author.id
        })
        console.log(data.expected, data.reason, Date.now())
        if (!data) return console.log("NO DATA")
        if (Date.now() > data.expected) {
            console.log(3)
            message.member.roles.remove("956942754502565908")
            message.member.roles.add("913070918404833300")
            message.member.roles.add("913071151427780698")
            client.channels.cache.get(channels.stafflogs).send({ embed: embed })
            message.channel.send("Welcome back from holiday!")
            return data.delete();
        }
    }

Console Output I got from above code.

1
undefined undefined 1668502797493

I tried to check wether timestamp saved in db is equal to or greater than the current timestamp so I can delete data.

CodePudding user response:

You should await your findOne call. Otherwise it will return just a promise, which does not have the properties expected or reason. Exchange your call with the following code:

const data = await holidaydata.findOne({
  staff: message.author.id
})
  • Related