我有一个要作为排序依据的对象数组.根据文档,顶层的 .sort() 是这样工作的:
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 })我尝试过这样的事情:
Product.findById(productId) .sort( { requests: { _id: -1 } } )但我收到以下错误:
TypeError: Invalid sort value: { requests: [object Object] }
TypeError: Invalid sort value: { requests: [object Object] }
如果我在 mongodb (compass) 中有这个顺序的对象 ID
If I have the object ID's in this order in mongodb (compass)
_id:123456789
_id: 123456789
_id:987654321
_id: 987654321
我希望 _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} ) 推荐答案来自 mongoose doc排序:
如果传递对象,则允许的值为 asc、desc、升序、降序、1 和 -1.
If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1.
您传递的值是一个对象 { _id: -1 },它只需要 -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 } )
如果它没有按您预期的方式工作,您也可以传递一个字符串而不是这样的对象:Product.findById(productId).sort('requests._id') 或 Product.findById(productId).sort('-requests._id')
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')
更多推荐
如何对对象数组 node.js 和 mongoose 进行排序
发布评论