I
I
ikerya2020-07-07 18:18:57
MongoDB
ikerya, 2020-07-07 18:18:57

How to build an aggregate query for mongoose?

Hello! I have a collection of posts:

{
  definition: { type: mongoose.Types.ObjectId, ref: 'Definition' }
}


There is also a collection of definitions:

{
  title: String,
  likes: Number
}


Question: how to pull out from the collection of posts those documents whose definition.likes > 10, for example? Using aggregate

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-07-07
@ikerya

mongus populate will not be able to combine with aggregation in one query,
try something like this

Post.aggregate([
  { 
    $lookup: {
      from: 'definitions',
      localField: 'definition',
      foreignField: '_id',
      as: 'definitions'
    } 
  },
  {
    $match: {
      'definitions.likes': { $gte: 10 }
    }
  }
])

(if it doesn’t work out, then I suggest poke aggregation in mongodb compass, each step will be very clearly signed there)
but in general, there is no reason to store likes and the title of the post separately from the post

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question