3

我一直在编写一个小型节点应用程序,部分查询是按对象的喜欢数排序,如下所示:

likes      : { num: { type: Number, default: 0 }, IDs:[Number]...

和排序查询:

Object.find().sort({likes : 'desc'};).execFind(function(err, confessions){...

这不按喜欢的数量排序(就像我想要的那样),而是按最近喜欢的对象排序。

我将如何按 likes.num 排序?我似乎无法让它工作......

编辑:继承人要求的 mongo 文档

{ __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){...
4

2 回答 2

6

答案是将查询参数用 Linda Quin 建议的引号括起来

sortParams = {'likes.num' : 'desc'};
于 2013-04-19T02:00:10.543 回答
0

您将获得按对象值排序的结果 - 问题是对象是完整的 JSON 文档。您真正想要的是按对象中特定字段的值排序,在您的情况下为“likes.num”

引号将包含在查询中:

 {"likes.num":-1} 
于 2013-04-18T23:15:16.390 回答