用于对猫鼬3.x填充文档进行排序的正确语法 [英] The correct syntax for sorting mongoose 3.x populated document

查看:67
本文介绍了用于对猫鼬3.x填充文档进行排序的正确语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个处于1:1关系的MongoDB集合CustomerUser.我正在尝试使用猫鼬种群来查询两个文档,并按User.name对其进行排序. /p>

以下任何内容均无效.我的猫鼬是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

解决方案

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

Mongo没有加入.排序填充文档的唯一方法是待办事项 收到所有结果后,请手动进行操作.

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

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

I have two MongoDB collections Customer and User in 1:1 relationship. I'm trying to query both documents using Mongoose Population and sort them by User.name.

Nothing below is working. My Mongoose is 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()

I found How to sort a populated document in find request?, but no success for me.

It would be something like below in SQL:

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

解决方案

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.

这篇关于用于对猫鼬3.x填充文档进行排序的正确语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆