So I have a dynamic variable being passed in that is the name of the field that I would like to sort on.
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
});
};
If you're using node v4, you can use the ES6 syntax:
find.sort({[sortVariable]: 1});
return Postings.find({
'device.name': filter.exactDevice
}, {
sort: {[sortVariable]: 1}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With