user8463989
user8463989

Reputation: 2459

how to sort array of objects node.js and mongoose

I have an array of objects that I want to sort by. .sort() at top level works like this according to documentation:

Product.findById(productId)
.sort({ somefield: -1 })

I have tried something like this:

 Product.findById(productId)
 .sort( { requests: { _id: -1 } } )

But I get the following error:

TypeError: Invalid sort value: { requests: [object Object] }

If I have the object ID's in this order in mongodb (compass)

_id: 123456789

_id: 987654321

I want _id 987654321 show first in the list.

I have even added a date field now and tried to sort by that but the order still stays the same as what the record was inserted in.

  Product.findById(productId)
  .sort( { 'requests.requestDt': 1} )

Upvotes: 0

Views: 2806

Answers (1)

pmar
pmar

Reputation: 314

From mongoose doc on sort:

If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1.

The value you are passing is an object { _id: -1 }, and it expects just the -1 (or one of the other valid values). If you change the key to be the full path to the item you want to sort, that should solve your problem.

Product.findById(productId) .sort( { 'requests._id': -1 } )

If it doesn't work the way you expected, you can also pass a string instead of an object like this: Product.findById(productId) .sort('requests._id') or Product.findById(productId) .sort('-requests._id')

Upvotes: 1

Related Questions