During my project using mongoose, I encountered a issue. I am trying to retrieve all documents that contain a specific key and value pair role: USER
. Although I am able to retrieve a list of documents, I am struggling to access the values of certain fields from it, no matter what approach I take.
Here is the code snippet:
const getUsersList = async () => {
const users = await userModel.find({ role: USER });
//I also attempted:
//In each case, I receive undefined
const users = await userModel.find({ role: USER }).userName;
////
const users = await userModel.find({ role: USER }).exec();
////
Document.prototype.toObject(users);
////
JSON.stringify(users).userName
}
The query is successfully fetching the documents, as console.log(users)
displays the retrieved documents.
[
{
_id: new ObjectId("618b1a587d57e9c8e78865e1"),
userName: 'Username1',
name: 'Fullname1',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee8b838f8782dfae89838f8782c08d8183">[email protected]</a>',
password: 'Password1',
status: 'INVITED',
role: 'USER',
__v: 0
},
{
_id: new ObjectId("618b1a6e7d57e9c8e78865e5"),
userName: 'Username3',
name: 'Fullname2',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec89818d8580deac8b818d8580c28f8381">[email protected]</a>',
password: 'Password2',
status: 'INVITED',
role: 'USER',
__v: 0
}
]
Based on the mongoose documentation, it seems like I am following the correct process. It suggests converting a document to an object using toObject()
, however, I am unable to find such a method available for the query in mongoose
My schema:
const userSchema = new Schema(
{
userName: { type: String, unique: true, required: true },
name: { type: String, required: true },
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
confirmationCode: { type: String, required: false },
status: { type: String, required: true, default: STATUS.INVITED },
role: { type: String, required: true, default: USER },
},
);