Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda