【问题标题】:MongoDb findOne result property is undefinedMongoDb findOne 结果属性未定义
【发布时间】:2021-09-04 11:18:32
【问题描述】:

我在模型中使用 findOne,它会返回响应。

    const findAccount = await this.accountModel.findOne({
        _id: ObjectId(param.accountId),
    });
     
    console.log(findAccount);
    //The above logs the data
    console.log(findAccount.role, findAccount._id);
    //As for this, findAccount.role is undefined, but the findAccount._id was logged.

可能是什么原因?

【问题讨论】:

  • 你能展示你的模型吗?

标签: node.js mongodb express mongoose nestjs


【解决方案1】:

findOne 方法返回一个 Mongoose 文档的实例,这可能会导致这样的情况。要获取 Javascript 纯对象,您可以使用 lean() method。试试这个:

    const findAccount = await this.accountModel.findOne({
        _id: ObjectId(param.accountId),
    }).lean();
     
    console.log(findAccount);
    //The above logs the data
    console.log(findAccount.role, findAccount._id);
   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 2021-05-29
    • 1970-01-01
    • 2018-10-01
    相关资源
    最近更新 更多