0

私は 2 つの MongoDB コレクションを持ってCustomerおりUser1:1関係にあります。Mongoose Populationを使用して両方のドキュメントをクエリし、 で並べ替えようとしていますUser.name

以下は何も機能していません。私のマングースは 3.8.19 です。

Customer
    .find({})
    .populate("user", "name email phone")
    .sort({ "name": 1 })
    .exec()

Customer
    .find({})
    .populate("user", "name email phone", null, { sort: { 'name': 1 } } )
    .exec()

Customer
    .find({})
    .populate({
        path: "user",
        select: "name email phone",
        options: { sort: { "name": 1 }}
    }).
    exec()

Customer
    .find({})
    .populate({
        path: "user",
        select: "name email phone",
        options: { sort: [{ "name": 1 }]}
    })
    .exec()

検索条件で入力されたドキュメントを並べ替える方法を見つけましたか? 、しかし私にとっては成功しません。

SQL では以下のようになります。

SELECT customer.*, user.name, user.email, user.phone FROM customer 
JOIN user ON customer.user_id = user.id
ORDER BY user.name ASC
4

2 に答える 2

5

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.

于 2014-12-08T03:55:21.030 に答える
1

人口の多いフィールドをソートできないと人々が言っ​​ている理由がわかりません....

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

私のモデルが「投稿」する場所には、ObjectID メッセージ配列があり、ここに入力され、createDate でソートされます。それはうまくいきます。

于 2015-08-01T02:28:00.787 に答える