MongoDb findOne 结果 属性 未定义

MongoDb findOne result property is undefined

我在模型中使用 findOne,它 returns 是一个响应。

    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.

可能是什么原因?

findOne 方法 returns 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);