本文介绍了Mongo按动态字段排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我传入了一个动态变量,该变量是我要排序的字段的名称.
So I have a dynamic variable being passed in that is the name of the field that I would like to sort on.
让我们说下面的sortVariable可以等于价格","createdAt",名称"等.这不起作用,我该怎么办?
Let's say sortVariable below could equal "price", "createdAt", "name" etc. This isn't working, how can I do this?
function findStuff (sortVariable) {
var postings = Postings.find({
"device.name": filter.exactDevice,
}, {
sort: {
sortVariable: 1
}
});
return postings;
}
推荐答案
您不能将变量用作对象常量中的键.试试看:
You can't use variables as keys in object literals. Give this a try:
var findStuff = function(sortVariable) {
var sort = {};
sort[sortVariable] = 1;
return Postings.find({
'device.name': filter.exactDevice
}, {
sort: sort
});
};
这篇关于Mongo按动态字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!