0

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

1 Answer 1

1

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')

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, no error but not sorting how I want. It should the last _id first in the list.
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
@pmar, thanks for the effort. I have edited my question to show how I want to sort the data. I tried all of your examples but it still sorts in the opposite order of how I want. I tried 1 instead of -1 as well and same result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.