Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

497
Visualizações
How to filter documents in Mongoose model with data from another models

For example, I have 3 models:

Stories:

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

Comments:

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

Likes:

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

How can I get the most popular stories, if popularity is determined by the amount of comments and likes? Story is more popular if it has more comments and likes, for example.

Thanks.

Upd: example data.

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

The result of filtering should be like this:

  1. First story (4 likes, 2 comments)
  2. Second story (2 likes, 1 comment)
  3. Third story (1 like)
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you want to sort data according to popularity where popularity is defined by (total like + total comments ) then you can use this aggregate query with $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}}
])

for mongoose:

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 
    })

OR if you want to sort by likes then comments or comments then like.

can use this query:

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 
})
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda