Using mongoose in my project, I ran into a problem.
I want to find all documents that have such a key and value pair role: USER
. I can get a list of documents, but I cannot get the values of specific fields from it, no matter how I try.
Here is my code:
JavaScript
x
14
14
1
const getUsersList = async () => {
2
const users = await userModel.find({ role: USER });
3
4
//also I truing:
5
//In each case, I get undefined
6
const users = await userModel.find({ role: USER }).userName;
7
////
8
const users = await userModel.find({ role: USER }).exec();
9
////
10
Document.prototype.toObject(users);
11
////
12
JSON.stringify(users).userName
13
}
14
The request definitely gets the document, because console.log(users)
lists the documents.
JavaScript
1
23
23
1
[
2
{
3
_id: new ObjectId("618b1a587d57e9c8e78865e1"),
4
userName: 'Username1',
5
name: 'Fullname1',
6
email: 'email1@gmail.com',
7
password: 'Password1',
8
status: 'INVITED',
9
role: 'USER',
10
__v: 0
11
},
12
{
13
_id: new ObjectId("618b1a6e7d57e9c8e78865e5"),
14
userName: 'Username3',
15
name: 'Fullname2',
16
email: 'email2@gmail.com',
17
password: 'Password2',
18
status: 'INVITED',
19
role: 'USER',
20
__v: 0
21
}
22
]
23
Judging by the documentation of the mongoose, I am doing everything right. It is also advised to cast a document into an object using toObject()
, but mongoose does not find such a method for request
Моя схема:
JavaScript
1
12
12
1
const userSchema = new Schema(
2
{
3
userName: { type: String, unique: true, required: true },
4
name: { type: String, required: true },
5
email: { type: String, unique: true, required: true },
6
password: { type: String, required: true },
7
confirmationCode: { type: String, required: false },
8
status: { type: String, required: true, default: STATUS.INVITED },
9
role: { type: String, required: true, default: USER },
10
},
11
);
12
Advertisement
Answer
It’s an array, so trying to get userName won’t work. You need to get the specific element. Try this:
JavaScript
1
3
1
const userResponse = await userModel.find({ role: USER })
2
const firstUserName = userResponse[0].userName
3