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

时间:2017-01-06 10:33:29

标签: node.js mongodb mongoose

例如,我有3个模型:

案例:

{
    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" }
}

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

感谢。

更新:示例数据。

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个喜欢)

1 个答案:

答案 0 :(得分:3)

如果您想根据受欢迎程度对数据进行排序,其中受欢迎程度由(总类似+总评论数)定义,那么您可以使用此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 
})