【问题标题】:Cannot read value after getting queried by model.find()被model.find()查询后无法读取值
【发布时间】:2021-12-08 20:42:47
【问题描述】:
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);" 但是当我尝试通过 console.log(check.userID) 读取其中的值时,它显示未定义。

这里是输出

【问题讨论】:

    标签: node.js mongodb mongoose discord.js


    【解决方案1】:

    find 返回文档数组,因此字段userID 不存在于数组中。

    如果您确定响应将只返回一份文档,请使用findOne

    【讨论】:

    • 非常感谢先生
    • 如果解决了您的问题,请将问题标记为答案。
    【解决方案2】:

    find 返回一个数组。您必须使用.forEach 来获取数组中的项目或使用findOne 来获取对象

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

    或者

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多