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

196
Views
mongoose do not display unnecessary lines from the array

I want to output sorted list from database.

I do so

const subs = await Sub.find({}, {userName: 1, score: 1, _id: 0}).sort({ score: 'desc' });

And in the end I get this list like this

{ userName: 'test1', score: 14 },{ userName: 'test2', score: 2 },{ userName: 'test3', score: 1 },{ userName: 'test4', score: 0 }

How can I remove unnecessary lines here so that something like this comes out in the response

'test1' score: 14, 'test2' score: 2, 'test3' score: 1, 'test4' score: 0

I work with tmi.js

async function leaderboardHandler(chan, userstate) {
  const subs = await Sub.aggregate([
    {$sort: {score: -1}},
    {$project: {_id: 0, res: [{k: "$userName", v: "$score"}]}},
    {$set: {res: {$arrayToObject: ["$res"]}}},
    {$replaceRoot: {newRoot: "$res"}}
  ])

  client.say(chan, `@${userstate.username} leaderboard: ${subs}`);
}
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

One option is using an aggregation pipeline with $arrayToObject:

db.collection.aggregate([
  {$sort: {score: -1}},
  {$project: {_id: 0, res: [{k: "$userName", v: "$score"}]}},
  {$set: {res: {$arrayToObject: ["$res"]}}},
  {$replaceRoot: {newRoot: "$res"}}
])

See how it works on the playground example

about 4 years ago · Santiago Gelvez 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!