node.js - 对 mongoose 3.x 填充文档进行排序的正确语法

标签 node.js mongodb sorting mongoose mongoose-populate

我有两个 CustomerUser 关系的 MongoDB 集合,它们的关系是1:1。我正在尝试使用 Mongoose Population 查询两个文档并按 User.name 对它们进行排序。

下面没有任何效果。我的 Mongoose 是 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()

我找到了How to sort a populated document in find request? ,但对我来说没有成功。

在 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 in comment ,无法对 MongoDB 和 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.

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

作为一个侧 Node ,我正在考虑使用 node.js 迁移到关系数据库。

关于node.js - 对 mongoose 3.x 填充文档进行排序的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27318115/

相关文章:

node.js - 如何根据当前日期对日志文件进行分类?

javascript - LDAP over TLS 在 Node 中使用 ldap-client

php - 你怎么知道一个集合是否有上限?

MongoDB:删除多个对象内的项目

java - 对用户输入的价格进行冒泡排序?

ruby-on-rails - Rails 3 复杂排序

node.js - NodeJS 迭代 JSON 中的 City,返回城市和每个城市的用户

javascript - 返回的 Promise 在 Node.js 中未定义

python - 如何通过 python 跟踪来自特定城市的推文并存储在 MongoDB 中?

python-2.7 - 如何在 ElasticSearch 中使用带有分页和排序的扫描/滚动?