如何对对象数组 node.js 和 mongoose 进行排序

编程入门 行业动态 更新时间:2024-10-22 18:45:32
本文介绍了如何对对象数组 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 进行排序

本文发布于:2023-11-22 19:20:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618689.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   node   js   mongoose

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!