Node.js 在mongoose查询中同时使用匹配、限制、排序和查找
我有两个学院:Node.js 在mongoose查询中同时使用匹配、限制、排序和查找,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有两个学院: 使用者 通知 用户: 通知: { id:1, userId:1, read:false, info: 'Notification for user 1' },{ id:2, userId:2, read:false, info: 'Notification for user 2' },{ id:3, userId:3, read:false, info: 'Notification for user 3' } 我想根据通知数据中的
{
id:1,
userId:1,
read:false,
info: 'Notification for user 1'
},{
id:2,
userId:2,
read:false,
info: 'Notification for user 2'
},{
id:3,
userId:3,
read:false,
info: 'Notification for user 3'
}
我想根据通知数据中的用户id,使用match(read:false)、sort(createdAt上的降序)、limit(5)和查找用户集合来获取通知数据
查询应返回:
[{
id:1,
userId:1,
read:false,
info: 'Notification for user 1'
username:ABC
},{
id:2,
userId:2,
read:false,
info: 'Notification for user 2'
username:ABC2
},{
id:3,
userId:3,
read:false,
info: 'Notification for user 3'
username:ABC3
}]
你可以试试
匹配您的条件$match
加入用户集合$lookup
解构用户数组,因为它是一个数组,我们需要对象$unwind
显示必填字段$project
按$sort
降序排序createdAt
5个文档$limit
匹配您的条件$match
加入用户集合$lookup
解构用户数组,因为它是一个数组,我们需要对象$unwind
显示必填字段$project
按$sort
降序排序createdAt
5个文档$limit
谢谢@turivishal抽出时间。这将在节点中返回“发送到客户端后无法设置头”。您需要提供如何使用和执行query.Notification.aggregate([{$match:{read:false}},{$lookup:{from:“users”,as:“user”,localField:“clientId”,foreignField:“id”}、{$unwind:$user”}、{$project:{id:1,clientId:1,read:1,username:$user”}、{$sort:{createdAt:-1}、{$limit:5}])。然后(…)我希望这能让问题变得更清楚@turivishalno请说明您是如何打印记录的,它返回了错误,我认为您必须查看mongoose中的文档谢谢@turivishal为您提供的时间。此返回“发送到客户端后无法设置标题”“在节点中,您需要提供如何使用和执行query.Notification.aggregate([{$match:{read:false}},{$lookup:{from:“users”,as:“user”,localField:“clientId”,foreignField:“id”},{$unwind:“$user”},”,{$project:{id:1,clientId:1,read:1,用户名:“$user”},{$sort:{createdAt:-1},{$limit:5}])。然后(…)我希望这能让问题变得更清楚@turivishalno请说明您是如何打印记录的,在哪里返回错误,我想您必须查看mongoose中的文档
[{
id:1,
userId:1,
read:false,
info: 'Notification for user 1'
username:ABC
},{
id:2,
userId:2,
read:false,
info: 'Notification for user 2'
username:ABC2
},{
id:3,
userId:3,
read:false,
info: 'Notification for user 3'
username:ABC3
}]
db.notification.aggregate([
{ $match: { read: false } },
{
$lookup: {
from: "user",
as: "user",
localField: "userId",
foreignField: "id"
}
},
{ $unwind: "$user" },
{
$project: {
id: 1,
userId: 1,
read: 1,
info: 1,
username: "$user.name"
}
},
{ $sort: { createdAt: -1 } },
{ $limit: 5 }
])