Skip to content

Destructuring a mongoose document

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:

  const getUsersList = async () => {
  const users = await userModel.find({ role: USER });

  //also I truing:
  //In each case, I get 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 request definitely gets the document, because console.log(users) lists the documents.

    [
  {
    _id: new ObjectId("618b1a587d57e9c8e78865e1"),
    userName: 'Username1',
    name: 'Fullname1',
    email: '[email protected]',
    password: 'Password1',
    status: 'INVITED',
    role: 'USER',
    __v: 0
  },
  {
    _id: new ObjectId("618b1a6e7d57e9c8e78865e5"),
    userName: 'Username3',
    name: 'Fullname2',
    email: '[email protected]',
    password: 'Password2',
    status: 'INVITED',
    role: 'USER',
    __v: 0
  }
]

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
Моя схема:

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

Answer

It’s an array, so trying to get userName won’t work. You need to get the specific element. Try this:

const userResponse = await userModel.find({ role: USER })
const firstUserName = userResponse[0].userName