fatiu
fatiu

Reputation: 1538

MongoDb findOne result property is undefined

I am using a findOne in a model and it returns a response.

    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.

What could be the cause?

Upvotes: 2

Views: 341

Answers (1)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

findOne method returns an instance of Mongoose document, which can lead to situations like this. To get the Javascript plain object, you can use lean() method. Try this:

    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);
   

Upvotes: 1

Related Questions