通过对象数组中的值查找
我无法查询特定部门中包含的所有配置文件。
我正在使用带有mongodb和mongoose的nodejs。下一个是Profile模式的示例:
Profile: {
"level": 1,
"departments": [
{
"_id": "5c5f3bb4338fde6c60a684d4",
"department": "5c106a324acd0571241323f2",
"name": "Calidad"
},
{
"_id": "5c5f3794eca3f14cd49e395e",
"department": "5c106bad99142733446a44f0",
"name": "Mantenimiento"
}
]
以下是我试过的查询:
Profile.find({ departments: [{ department: req.params.id }] })
.then(profiles => res.json(profiles))
.catch(err =>
res.status(404).json({ nodepartmentfound: "No departments found" })
);
我希望返回包含指定部门的所有配置文件的tan数组。
回答如下:请尝试以下代码:
Profile.find({ "departments.department": req.params.id })
.then(profiles => res.json(profiles))
.catch(err =>
res.status(404).json({ nodepartmentfound: "No departments found" })
);
基本上,您要做的是查询嵌入文档的数组。使用点符号足以解决您的问题。相关文档可以在here找到。
通过对象数组中的值查找
我无法查询特定部门中包含的所有配置文件。
我正在使用带有mongodb和mongoose的nodejs。下一个是Profile模式的示例:
Profile: {
"level": 1,
"departments": [
{
"_id": "5c5f3bb4338fde6c60a684d4",
"department": "5c106a324acd0571241323f2",
"name": "Calidad"
},
{
"_id": "5c5f3794eca3f14cd49e395e",
"department": "5c106bad99142733446a44f0",
"name": "Mantenimiento"
}
]
以下是我试过的查询:
Profile.find({ departments: [{ department: req.params.id }] })
.then(profiles => res.json(profiles))
.catch(err =>
res.status(404).json({ nodepartmentfound: "No departments found" })
);
我希望返回包含指定部门的所有配置文件的tan数组。
回答如下:请尝试以下代码:
Profile.find({ "departments.department": req.params.id })
.then(profiles => res.json(profiles))
.catch(err =>
res.status(404).json({ nodepartmentfound: "No departments found" })
);
基本上,您要做的是查询嵌入文档的数组。使用点符号足以解决您的问题。相关文档可以在here找到。