我一直在编写一个小节点应用程序,部分查询按照对象的喜欢数量进行排序,如下所示:
likes : { num: { type: Number, default: 0 }, IDs:[Number]...
和排序查询:
Object.find().sort({likes : 'desc'};).execFind(function(err, confessions){...
这并不是根据喜欢的数量排序(就像我想要的那样),而是按照最近喜欢的对象进行排序。
我如何按likes.num排序?我似乎无法让它工作......
编辑:根据要求提供mongo doc
{ __v: 0,
_id: 51703a470ef8e60000000002,
name: 'Name',
text: ' this is a fresh submission for mongo to hold',
comments: { commentData: [], num: 0 },
removed: false,
time: Thu Apr 18 2013 11:24:07 GMT-0700 (PDT),
likes: { IDs: [ 100001810858894 ], num: 1 },
dislikes: { IDs: [ 100001810858894 ], num: 1 } }
编辑:继承整个查询
exports.index = function (req, res) {
console.log(req.user);
var sortParams;
var sort = req.params.sortingMethod;
console.log(sort);
if (sort == 'newest'){
sortParams = { time : 'asc'};
} else if (sort == 'oldest'){
sortParams = { time : 'desc'};
} else if (sort == 'likes'){
sortParams = {likes.num : 'desc'};
} else if (sort == 'dislikes'){
sortParams = {dislikes.num :'desc'};
} else {
sortParams = { time : 'desc'};
}
console.log(sortParams);
Confession.find().sort(sortParams).execFind(function(err, confessions){...
答案 0 :(得分:0)
您将按对象的值排序结果 - 问题是该对象是完整的JSON文档。你真正想要的是按对象中特定字段的值进行排序,在你喜欢的情况下是“likes.num”
引号将包含在查询中:
{"likes.num":-1}
答案 1 :(得分:0)
答案是将查询参数包装在像Linda Quin建议的引号中
sortParams = {'likes.num' : 'desc'};