Babak Abadkheir
Babak Abadkheir

Reputation: 2358

mongoose populate sort _ Mongoose Node.js

I have two schemas that represent my post and category documents. I'm trying to sort my posts with category.order property. order property is a number field.

const postSchema = mongoose.Schema({
    title: {
        type: String,
        max: 200,
    },
    body: {
        type: String,
        max: 10000,
    },
    categories: {
        type: mongoose.Schema.ObjectId,
        ref: 'Category',
        required: true
    }
})
module.exports = mongoose.model('Post', postSchema);


const categorySchema = mongoose.Schema({
    name: {
        type: String,
        max: 30,
        required:true
    },
    order: {
        type: Number,
        unique: true
    },
})
module.exports = mongoose.model('Category', categorySchema);

I know sort only works with numeric fields. I searched a lot about the simular problem in web and StackOverflow even the mongoose documention.but my query doesn't work. it gets my post back but sorting order is not working. query:

Post.find({}).populate({path:'categories', select:'order', options:{sort:{order:1}}})

Upvotes: 2

Views: 87

Answers (1)

Ashh
Ashh

Reputation: 46491

Well populate does not sort the root/outer documents. The options passed in the populate only sorts the inner referenced documents. You have to use aggregation here to make sorting on the parent documents and that's what $lookup can better do as compared to populate queries.

Post.aggregate([
  { '$lookup': {
    'from': 'categories',
    'let': { 'categories': '$categories' },
    'pipeline': [
      { '$match': { '$expr': { '$eq': ['$_id', '$$categories'] }}},
      { '$project': { 'order': 1 }}
    ],
    'as': 'categories'
  }},
  { '$unwind': '$categories' },
  { '$sort': { 'categories.order': 1 }}
])

Upvotes: 2

Related Questions