Home > database >  mongoose display sorted list
mongoose display sorted list

Time:07-17

I want to output sorted list from database

I do so

const subs = await Sub.find().sort({ score: 'desc' });

And in the end I get this list like this

{ _id: new ObjectId("62d2eeefbb2b98ccb13cb3e4"), userName: 'test1', score: 4, __v: 0 },{ _id: new ObjectId("62d2f7f52bc154430fb538eb"), userName: 'test2', score: 2, __v: 0 },{ _id: new ObjectId("62d2f4dca0beed6184b124d2"), userName: 'test3', score: 1, __v: 0 }

How can I make the list show only the userName and score values?

CodePudding user response:

The find method takes a second optional argument which is referred to as projection. It allows you to define the fields you want to return. For your scenario to return only the username and score you would write

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

When using the projection stage, passing 1 as a value to means you want the value returned in the query and passing 0 means you don't want the value to be returned in the query.

Hope this helps

  • Related