Quang Nguyen
Quang Nguyen

Reputation: 23

Mongoose sort and search document by populated field

I have collections user, news, and user-news."user-news" populated to "user" and "news".

Can I sort and search document of "user-news" by "user.name" or "news.title" ?

const usersSchema = new Schema({ name: String })

const newsSchema = new Schema({ title: String }),

UsersNewsModel.find(queryObj)
    .populate('user', 'name')
    .populate('news', 'title')
    .sort({ 'user.name': -1 })
    .exec((findError, records) => {...}

Upvotes: 2

Views: 1455

Answers (1)

Delgee B
Delgee B

Reputation: 166

Mongoose populate doesn't support sorting from populated field. But you can do something like this with aggregate.

UsersNewsModel.aggregate([
  {
    $lookup: {
        from        : 'user',
        localField  : 'user',
        foreignField: '_id',
        as          : 'user'
    }
  },
  {
    $unwind: {
      path: $user
    }
  },
  {
    $sort: {
      'user.name': -1
    }
  }
])

Upvotes: 4

Related Questions