gpt4 book ai didi

node.js - Mongoose (Mongodb)按填充字段排序

转载 作者:可可西里 更新时间:2023-11-01 09:47:29 32 4
gpt4 key购买 nike

我有一个 Product 模型,每个产品都有一个 category 字段。这个类别字段由 mongoose 使用 Category 集合中匹配文档的字段填充。我这样做是希望通过 category.popularity 对我的产品查询进行排序,这只是一个简单的数字。这里的目标是当您按流行排序时,查询排名最高的第一位。我整晚都在搜索并实现了不同的使用排序方式,但我要么误解了它的工作原理,要么只是没有正确使用。这是我获取产品的电话

const docs = await models.products
.find(find, null, opts)
.populate('retailer')
.populate({
path : 'category',
select : 'popularity',
options : { sort : { popularity : -1 } }
})

这会正确填充字段,但不会对其进行排序。这是我按类别受欢迎程度对产品进行排序的正确方法吗?我很想听听您的意见,如果您需要更多信息,请告诉我。谢谢!

最佳答案

填充无助于对 ROOT/父集合进行排序,也不是对两个集合执行连接的更好选择。

您必须使用一些替代方案,例如 $lookup获取关于子集合的排序文档。

const docs = await models.products.aggregate([
{ "$match": { find }},
{ "$lookup": {
"from": Retailer.collection.name,
"localField": "retailer",
"foreignField": "_id",
"as": "retailer"
}},
{ "$lookup": {
"from": Category.collection.name,
"localField": "category",
"foreignField": "_id",
"as": "category"
}},
{ "$unwind": "$category" },
{ "$sort": { "category.popularity": 1 }}
])

关于node.js - Mongoose (Mongodb)按填充字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56437015/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com