这是关于喜欢和不喜欢的评论。我想按相似程度对评论进行排序,所以首先会出现一个更喜欢的评论。问题是,与不喜欢的评论相比,不喜欢的评论出现在前面。
我想要的:
我真正得到的是:
我的蒙戈询问我的流星助手:
Missatges.find({ topic: 'xxx' }, { sort: { like:{ $size: -1}, dislike:{ $size: 1}, date: -1 } }).fetch();请注意,我使用$size是因为and和are是user _id的数组。
author: {
type: String
},
authorId: {
type: SimpleSchema.RegEx.Id
}
isAnswer: {
type: Boolean
},
parentId: {
type: SimpleSchema.RegEx.Id,
optional: true
},
date: {
type: Date
},
topic: {
type: String
},
likes: {
type: [SimpleSchema.RegEx.Id]
},
dislikes: {
type: [SimpleSchema.RegEx.Id]
},
answers: {
type: [SimpleSchema.RegEx.Id],
optional: true
},
text: {
type: String,
max: 900,
}发布于 2016-06-03 12:27:02
根据this question的答案,您不能使用$size对mongo进行排序。一种解决方案是对匹配的文档进行fetch,并在帮助器中对它们进行sort。下面是一个示例(注意,这是未经测试的,可能需要进行一些调整):
Template.something.helpers({
sortedThings: function () {
return Missatges
.find({ topic: 'xxx' })
.fetch()
.sort(function (b, a) {
var al = a.likes.length;
var ad = a.dislikes.length;
var bl = a.likes.length;
var bd = a.dislikes.length;
var d1 = a.date;
var d2 = b.date;
// compare by likes
if (al > bl) return 1;
if (al < bl) return -1;
// compare by dislikes
if (ad < bd) return 1;
if (ad > bd) return -1;
// compare by date
if (d1 > d2) return 1;
if (d1 < d2) return -1;
// they are equal
return 0;
});
},
});https://stackoverflow.com/questions/37612799
复制相似问题