gpt4 book ai didi

node.js - Mongoose 按对象的对象值排序

转载 作者:行者123 更新时间:2023-12-04 12:52:54 24 4
gpt4 key购买 nike

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

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

最佳答案

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

sortParams = {'likes.num' : 'desc'};

关于node.js - Mongoose 按对象的对象值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16094468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com