Home > other >  mongoose do not display unnecessary lines from the array
mongoose do not display unnecessary lines from the array

Time:07-17

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}`);
}

CodePudding user response:

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

  • Related