Home > Mobile >  Using MongoDB query to show all items in a Collection with a specific value (DiscordJS v13)
Using MongoDB query to show all items in a Collection with a specific value (DiscordJS v13)

Time:02-10

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.

CodePudding user response:

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;

CodePudding user response:

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);
        
     }
  • Related