Home > front end >  Mongoose sorting by populated field
Mongoose sorting by populated field

Time:10-25

In my Task schema I have fields like this:

{
  name: String
},
{
  user: ObjectID
}

I need to sort tasks. If I want to do it by name field it's easy:

await Tasks.find().sort({name: 1})

That works. But the problem is when I want to sort by user.name. To get fields from User I can populate them, so:

await Tasks.find().populate('user', 'name').sort({'user.name': 1})

And it doesn't work. I cannot sort by fields added by populate function. I've been searching a lot in documentation and in other users' questions. I've found that I can pass sorting option to populate function but it doesn't work also. I guess it sort fields in populated field.

When I've tried to use aggregate with lookup like this:

Tasks.aggregate([{ $lookup: {
{
   from: 'User',
   localField: 'user',
   foreignField: '_id',
   as: 'someField'
 }}}])

it returns someField: []

Can somebody help me? Thanks a lot!

CodePudding user response:

In aggregate query, you should reference your collection with it's real name, NOT with the model name. So, instead of from: 'User', it should be from: 'users':

Tasks.aggregate([
  { 
    $lookup: {
      from: 'users',
      localField: 'user',
      foreignField: '_id',
      as: 'user'
    }
  },
  {
    $set: {
      user: { $first: '$user' }
    }
  },
  {
    $sort: {
      'user.name': 1 
    }
  }
])
  • Related