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

227
Vistas
Using MongoDB query to show all items in a Collection with a specific value (DiscordJS v13)

I'm trying to make my last command for my discord bot (Discord.js v13), a marketplace with a MongoDB Collection called "Perso".

The problem is that I really don't know how to make it work, even after reading MongoDB and mongoose documentation, also searching similar (not really) problems on Stack Overflow.

Here is the little piece of code I did to test a return of value :

    let persoOnSale = await Perso.count({ onSale: 1}); // There are 2 "Perso" with the "onSale" field equals to 1.
    let perso = Perso.find({ onSale: 1}, 'name value').sort({value: 1});


     for (let index = 0; index < persoOnSale; index++) {
         const element = perso[index];
         console.log(element); // element return "undefined", 2 times.
        
     }

Here is the console.log return when it's console.log(perso) :

[
  {
    _id: new ObjectId("61fc60165a048fa5700de25d"),
    name: 'Perso Name',
    value: 160
  },
  {
    _id: new ObjectId("61fbe486ef3f2c2b31c57dc5"),
    name: 'Perso Name 2',
    value: 10000
  }
]

I was trying to show all the "Perso" with (onSale: 1), showing their name and value, and sort them in order to show the "Perso" with the least value amount first.

First of all, I imagine I need to put an index on the "perso" array, but I clearly don't know how to do that.

I'd be really thankful for your help.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I just found out.

I have to put an await before "Perso.find"

let perso = await Perso.find({ onSale: 1}, 'name value').sort({value: 1});

(Now, the "Persos" are found).

Then, I have to add that :

const element = perso[index].name;
const value = perso[index].value;
about 4 years ago · Juan Pablo Isaza Denunciar

0

I guess your problem comes from the usage of findOne() instead of find()

Try this:

    let persoOnSale = await Perso.count({ onSale: 1});
    let perso = Perso.find({ onSale: 1}, 'name value').sort({value: 1});


     for (let index = 0; index < persoOnSale; index++) {
         const element = perso[index];
         console.log(element);
        
     }
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