Node.js Can';t在mongodb中使用ID连接集合
我正在尝试根据请求状态从请求集合获取用户的所有请求。我正在尝试查找集合,但它不起作用。有什么解决办法吗 这是我的密码:Node.js Can';t在mongodb中使用ID连接集合,node.js,mongodb,express,match,Node.js,Mongodb,Express,Match,我正在尝试根据请求状态从请求集合获取用户的所有请求。我正在尝试查找集合,但它不起作用。有什么解决办法吗 这是我的密码: Users.aggregate([ { $lookup: { from: 'requests', let: {userId: '$userId', status: '$status'}, pipeline: [
Users.aggregate([
{
$lookup: {
from: 'requests',
let: {userId: '$userId', status: '$status'},
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$_id', '$$userId'] },
{ $eq: ['$$status', 1] }
]
},
}
}
],
as: 'requests'
}
}
]).exec()
我认为{$eq:['$\u id','$$userId']}
不起作用。我尝试使用$toObjectId
,但结果仍然相同
以下是用户的测试数据:
{
"_id": {
"$oid": "5f1c0112ad207a13308a3fea"
},
"createDate": {
"$date": "2020-07-25T09:52:58.678Z"
},
"userRole": 10,
"status": 1,
"fullName": "Test Name",
"email": "test.name@mailinator.com",
"password": "$2b$10$HQN//qFTQKW8tBnf7G0OV.Uta0zNbxd1hPlGVwvLp5CVIf49Y5PNW",
"__v": 0,
"profileImage": "1595957619296.jpg"
}
和测试请求数据:
{
"_id": {
"$oid": "5f2178c578153018ca5d79e8"
},
"request": "This is a demo request.",
"userId": {
"$oid": "5f1c0112ad207a13308a3fea"
},
"createDate": {
"$date": "2020-07-28T18:30:00.000Z"
},
"status": 1
}
您的查询中几乎没有修复程序
您的用户文档$match
为1,如果您不想,则可以排除状态
带请求$lookup
让
来自用户集合,因此添加用户集合\u id以便更正它用户id
- 无需创建
变量,因为我们已经检查了上述中的条件status
首先检查的是请求集合$eq
,其次是我们在上面的$userId
中创建了变量并使用let
,因为它引用的是主集合用户$$userId
变量let
- 第二个
检查$eq
在requests集合中为1,您在user集合中执行了该操作,我们已经在上面的$match条件中使用了该选项$status
工作场所:您能在问题中添加两个集合的示例数据吗。@turivishal我已经在问题中添加了测试数据。谢谢另一种方法是:
db.users.aggregate([
{
$match: {
status: 1
}
},
{
$lookup: {
from: "requests",
let: {
userId: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$userId",
"$$userId"
]
},
{
$eq: [
"$status",
1
]
}
]
}
}
}
],
as: "requests"
}
}
])