I have collections user, news, and user-news."user-news" populated to "user" and "news".
我有集合用户,新闻,和用户新闻。“用户新闻”填充为“用户”和“新闻”。
Can I sort and search document of "user-news" by "user.name" or "news.title" ?
我可以根据“user.name”或“news”对“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) => {...}
1 个解决方案
#1
2
Mongoose populate doesn't support sorting from populated field. But you can do something like this with aggregate.
Mongoose填充不支持从填充字段中排序。但是你可以用聚合来做类似的事情。
UsersNewsModel.aggregate([
{
$lookup: {
from : 'user',
localField : 'user',
foreignField: '_id',
as : 'user'
}
},
{
$unwind: {
path: $user
}
},
{
$sort: {
'user.name': -1
}
}
])
#1
2
Mongoose populate doesn't support sorting from populated field. But you can do something like this with aggregate.
Mongoose填充不支持从填充字段中排序。但是你可以用聚合来做类似的事情。
UsersNewsModel.aggregate([
{
$lookup: {
from : 'user',
localField : 'user',
foreignField: '_id',
as : 'user'
}
},
{
$unwind: {
path: $user
}
},
{
$sort: {
'user.name': -1
}
}
])