Shan Robertson
Shan Robertson

Reputation: 2742

Mongoose (Mongodb) sorting by populated field

I've got a Product model, and each product has a category field. This category field get's populated, by mongoose, with the fields from the matching document in the Category collection. I am doing this in hopes to sort my product query by category.popularity which is just a simple number. The goal here is when you sort by popular, the query is ranked with the highest number first. I've been searching all night and implementing different ways of using sort but i'm either misunderstanding how it works or just not doing it right. Here is my call to get the products

const docs = await models.products
      .find(find, null, opts)
      .populate('retailer')
      .populate({
        path : 'category',
        select : 'popularity',
        options : { sort : { popularity : -1 } }
      })

This populates the field correctly, but does not sort it. Is this the correct way I would sort my products by their categories popularity? I've love to hear what you have to say, and if you need any more info, please let me know. Thanks!

Upvotes: 4

Views: 1658

Answers (1)

Ashh
Ashh

Reputation: 46441

Populate does not help to sort the ROOT/parent collection and also not a better option to perform join on two collections.

You have to use some alternative like $lookup to get the sorted documents with with respect to child collection.

const docs = await models.products.aggregate([
  { "$match": { find }},
  { "$lookup": {
    "from": Retailer.collection.name,
    "localField": "retailer",
    "foreignField": "_id",
    "as": "retailer"
  }},
  { "$lookup": {
    "from": Category.collection.name,
    "localField": "category",
    "foreignField": "_id",
    "as": "category"
  }},
  { "$unwind": "$category" },
  { "$sort": { "category.popularity": 1 }}
])

Upvotes: 2

Related Questions