Home > Enterprise >  Cannot read value after getting queried by model.find()
Cannot read value after getting queried by model.find()

Time:10-22

exports.start = async (message) => {

let check = await profile.find({userID:message.author.id});
console.log(check);
console.log(check.userID);

try{
    let userAdd = new profile({
        userID: message.author.id,
        ServerID: message.guildId,
        level: 1,
    });
    const savedUser = await userAdd.save();
    message.channel.send(embedbuilder(`${message.author} has joined!`))
} catch(err) {
    message.channel.send(embedbuilder("Error joining the event"))
}

}

"console.log(check);" but when i try to read a value inside it by console.log(check.userID) it says undefined.

here the output

output

CodePudding user response:

find returns array of documents so the fields userID does not exist on an array.

If you are sure that response will return exactly one document then use findOne.

CodePudding user response:

find returns an array. You have to use .forEach to get the items in array or use findOne to get an object

let check = await profile.find({userID:message.author.id});
console.log(check);
check.forEach((item) => {
  console.log(item.userID)
})

Or

let check = await profile.findOne({userID:message.author.id});
console.log(check);
console.log(check.userID);
  • Related