首页 > 解决方案 > 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.

标签: javascriptnode.jsmongodbmongoose

解决方案


当使用带有属性名称的减号进行 Mongoose 排序时,您只需传递字符串本身,而不是对象:

.sort('payment.cash.budget')  // Ascending

.sort('-payment.cash.budget') // Descending

推荐阅读