我有两个 Customer
和 User
关系的 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/