0

我有两个 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

感谢@JohnnyHK 的评论,无法对 MongoDB 和 Moongose 中的填充字段进行排序。唯一的选择是手动对整个结果数组进行排序

Mongo 没有连接。对填充的文档进行排序的唯一方法是在收到所有结果后手动进行。

我通过使用Array.sort([compareFunction])对 Mongoose 查询的输出进行排序来解决这个问题。但是,在对大量数据进行排序时,它可能会对性能产生很大影响。

作为一个侧节点,我正在考虑使用 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 回答