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

225
Views
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 answers
Answer question

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 Report

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 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!