javascript - How to sort by object property with a minus sign in mongoose?
问题描述
I am trying to sort in mongoose by using the minus sign with the property and it seems to work fine (both ways) if I do directly on the property. So something like this works for me:
.sort({ name: -1 })
and this also works
.sort({ '-name': -1 })
But when I try to sort on the basis of a sub-property, it works only one way,
{ 'payment.cash.budget': -1 }
Above query works fine. But the following doesn't work:
{ '-payment.cash.budget': -1 }
Any reason why mongoose is behaving that way? I can't use (easily) use '1' instead of '-1' because the query comes from the front end.
- Mongoose: 4.13.0
- MongoDB: 3.6
解决方案
当使用带有属性名称的减号进行 Mongoose 排序时,您只需传递字符串本身,而不是对象:
.sort('payment.cash.budget') // Ascending
.sort('-payment.cash.budget') // Descending
推荐阅读
- python - 如何在路由的装饰器中捕获错误并使用 JSON 响应进行响应
- react-native - 如何在 React Native 中制作一个包含图标和以省略号结尾的标题的按钮?
- javascript - 如何在 Angular 中忽略 URL 继承
- vue.js - Vuejs Fullcalendar事件未显示
- tensorflow - TypeError:“图像”对象不能使用 PIL 进行下标
- javascript - 单击方法不起作用 - 将 selenium webdriver 与 java 一起使用
- reactjs - 使用 Hooks 将数据从子组件传递到父组件
- ios - 如何更新包含自定义标签的 React Native ScrollView 的 contentSize?
- c# - 为什么函数不能异步工作
- delphi - Delphi - 将变量传递给另一种形式(没有全局变量)