I was trying to create a leaderboard in Mongoose by merging two fields
which is the cash
and the bank
. I also have sorting
the cash and bank individually by using:
account.find({})
.sort([['cash', 'descending']])
.exec((err, res) => {
//Some code here
})
Same with the bank:
account.find({})
.sort([['bank', 'descending']])
.exec((err, res) => {
//Some code here
})
But I wanted to do also by merging those two fields and then do sorting them for my Overall Leaderboard
What I tried so far is:
account.find({})
.sort([['cash' 'bank', 'descending']])
.exec((err, res) => {
//Some code here
})
//Leads to shuffle list
also tried:
account.find({})
.sort([['cash \n bank', 'descending']])
.exec((err, res) => {
//Some code here
}) //Leads to Shuffled list
Lastly:
account.find({})
.sort([['cash', 'bank', 'descending']])
.exec((err, res) => {
//Some code here
})
//Leads to Error: Invalid sort value: [ ' field ', ' value ' ]
CodePudding user response:
We have a same code lines before I was creating a leaderboard. Then I figured it out how to merge the two fields in one embed.
You can use .sort
inside of .exec
.
If you are using a for loop
You need to put the .sort
inside of your for loop
account.find({})
.exec((err, res) => {
for(i = 0; i < res.length; i ) {
if(res.length === 0) {
//Some message for non existing data
} else if(res.length > 0) {
const a = await account.find({}).sort([['cash', 'descending']])
const b = await account.find({}).sort([['bank', 'descending']])
//Then Calling your sorted fields.
console.log(`${a[i].cash}`)
console.log(`${b[i].bank}`)
}
//If you are using embed or normal message. Call it after the for loop
message.channel.send(`${a[i].cash}`)
embed.addField(`Something here`, `${a[i].cash}`)
embed.addField(`Something here`, `${b[i].bank}`)
message.channel.send({embeds: [embed]})
}
})
EDIT:
But if you really need to merge the two fields. You might need to use aggregate query.