排序mongoose 3.x填充文档的正确语法

Sit*_*thu 0 sorting mongoose mongodb node.js mongoose-populate

我有两个MongoDB的集合CustomerUser1: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()
Run Code Online (Sandbox Code Playgroud)

我找到了如何在查找请求中对填充的文档进行排序?,但对我来说没有成功.

这将是SQL中的下面内容:

SELECT customer.*, user.name, user.email, user.phone FROM customer 
JOIN user ON customer.user_id = user.id
ORDER BY user.name ASC
Run Code Online (Sandbox Code Playgroud)

Sit*_*thu 5

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

Mongo没有加入.排序已填充文档的唯一方法是在收到所有结果后手动对其进行处理.

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

作为一个副节点,我正在考虑使用node.js迁移到关系数据库.