2

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

1 Answer 1

2

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 }}
])
Sign up to request clarification or add additional context in comments.

4 Comments

tnx for replying in short time, I 've been edit my code in question section about schemas . I tried your query but comes with empty array .
Sorry I made mistake. Now updated my answer. Please try it again
tnx you are my savior . another quetion . is sort can accept : ["acs" , "dec"] not number I mean
No and why you need 'asc' and 'dsc'. 1 and -1 does the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.