如何对对象数组 node.js 和 mongoose 进行排序 [英] how to sort array of objects node.js and mongoose

查看:83
本文介绍了如何对对象数组 node.js 和 mongoose 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要作为排序依据的对象数组.根据文档,顶层的 .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 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆