The correct syntax for sorting mongoose 3.x populated document

前端 未结 2 548
野性不改
野性不改 2021-01-07 15:52

I have two MongoDB collections Customer and User in 1:1 relationship. I\'m trying to query both documents using Mongoose Population an

相关标签:
2条回答
  • 2021-01-07 15:55

    I don't know why people are saying you can't sort a populated field....

    model.findOne({name: request.params.posts})
        .populate('messages', '_id message createDate', null, { sort: { 'createDate': -1 } })
        .exec(function(error, results) {
    })
    

    Where my model "posts", has a ObjectID messages array in it, that is populated here and sorted by it's createDate. It works great.

    0 讨论(0)
  • 2021-01-07 16:21

    Thanks to @JohnnyHK in comment, it is not possible to sort the populated fields in MongoDB and Moongose. The only option is to sort the entire array of results manually.

    Mongo has no joins. The only way to sort populated documents is todo it manually after you receive all results.

    I solved this by using Array.sort([compareFunction]) to sort the output resulted from Mongoose query. However, it could be a big impact on performance when sorting a large set of data.

    As a side node, I'm considering to move to a relational database with node.js.

    0 讨论(0)
提交回复
热议问题