如何用其他模型的数据过滤Mongoose模型中的文档



例如,我有三个模型:

故事:

{
title: { type: String },
text: { type: String }
}

评论:

{
text: { type: String },
story: { type: mongoose.Schema.Types.ObjectId, ref: "Stories" }
}

喜欢:

{
story: { type: mongoose.Schema.Types.ObjectId, ref: "Stories" }
}

如果受欢迎程度取决于评论和点赞的数量,我如何才能获得最受欢迎的故事?例如,如果故事有更多的评论和点赞,它就会更受欢迎。

谢谢。

Upd:示例数据

Stories: 
{
"title": "First story",
"text": "This must be the MOST popular story..."
}
{
"title": "Second story",
"text": "This story is popular too, but not as the first story."
}
{
"title": "Third story",
"text": "This is a unpopular story, because dont have any comment or like"
}

Comments:
{
"title": "Foo",
"story": ObjectId("First Story ID")
}
{
"title": "Foobar",
"story": ObjectId("First Story ID")
}
{
"title": "Bar",
"story": ObjectId("Second Story ID")
}

Likes:
{ "story": ObjectId("First Story ID") }
{ "story": ObjectId("First Story ID") }
{ "story": ObjectId("First Story ID") }
{ "story": ObjectId("First Story ID") }
{ "story": ObjectId("Second Story ID") }
{ "story": ObjectId("Second Story ID") }
{ "story": ObjectId("Third Story ID") }

过滤的结果应该是这样的:

  1. 第一个故事(4个赞,2条评论)
  2. 第二个故事(2个赞,1条评论)
  3. 第三层(1个赞)

如果您想根据受欢迎程度对数据进行排序,其中受欢迎程度由定义(点赞总数+评论总数),那么您可以将此aggregate查询与$lookup一起使用。

db.getCollection('stories').aggregate([
{$lookup:{from:"comments",localField:"_id", foreignField:"story", as:"comments"}},
{$lookup:{from:"likes",localField:"_id", foreignField:"story", as:"likes"}},
{ $project: { title: 1, text: 1,comments:1,likes:1, count: { $add: [ {$size: "$comments"}, {$size: "$likes"} ] } } },
{$sort:{"count":-1}}
])

猫鼬:

StoryModelName.aggregate([
{$lookup:{from:"comments",localField:"_id", foreignField:"story", as:"comments"}},
{$lookup:{from:"likes",localField:"_id", foreignField:"story", as:"likes"}},
{ $project: { title: 1, text: 1,comments:1,likes:1, count: { $add: [ {$size: "$comments"}, {$size: "$likes"} ] } } },
{$sort:{"count":-1}}
]).exec(function(err, values) {
if(err) {
// return error
}     
// return values 
})

如果您想按点赞然后评论评论排序,然后点赞

可以使用此查询:

StoryModelName.aggregate([
{$lookup:{from:"comments",localField:"_id", foreignField:"story", as:"comments"}},
{$lookup:{from:"likes",localField:"_id", foreignField:"story", as:"likes"}},
{$group:{_id:"$_id", 
totalLikes: {$sum:{$size: "$likes"}}, 
totalComments:{$sum:{$size: "$comments"}},
likes:{$first:"$likes"},
comments:{$first:"$comments"}
}
},
{$sort:{totalLikes:-1,totalComments:-1}} // can be comments ten like as you need
]).exec(function(err, values) {
if(err) {
// return error
}     
// return values 
})

最新更新