Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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: 'email1@gmail.com',
    password: 'Password1',
    status: 'INVITED',
    role: 'USER',
    __v: 0
  },
  {
    _id: new ObjectId("618b1a6e7d57e9c8e78865e5"),
    userName: 'Username3',
    name: 'Fullname2',
    email: 'email2@gmail.com',
    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 },
  },
);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!