gpt4 book ai didi

node.js - Mongoose 按填充字段排序和搜索文档

转载 作者:可可西里 更新时间:2023-11-01 10:00:07 25 4
gpt4 key购买 nike

我收集了用户、新闻和用户新闻。“用户新闻”填充到“用户”和“新闻”。

我可以按“user.name”或“news.title”对“user-news”文档进行排序和搜索吗?

const usersSchema = new Schema({ name: String })

const newsSchema = new Schema({ title: String }),

UsersNewsModel.find(queryObj)
.populate('user', 'name')
.populate('news', 'title')
.sort({ 'user.name': -1 })
.exec((findError, records) => {...}

最佳答案

Mongoose populate 不支持从填充字段排序。但是你可以用聚合做这样的事情。

UsersNewsModel.aggregate([
{
$lookup: {
from : 'user',
localField : 'user',
foreignField: '_id',
as : 'user'
}
},
{
$unwind: {
path: $user
}
},
{
$sort: {
'user.name': -1
}
}
])

关于node.js - Mongoose 按填充字段排序和搜索文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757495/

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