【问题标题】:Find by a value in an object array按对象数组中的值查找
【发布时间】:2019-02-17 03:58:37
【问题描述】:

我无法查询特定部门中包含的所有个人资料。

我将 nodejs 与 mongo 和 mongoose 一起使用。下面是一个 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 数组。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    试试下面的代码:

    Profile.find({ "departments.department": req.params.id })
      .then(profiles => res.json(profiles))
      .catch(err =>
        res.status(404).json({ nodepartmentfound: "No departments found" })
      );
    

    基本上,您要做的是查询嵌入文档的数组。使用点符号足以解决您的问题。相关文档可以在here找到。

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 1970-01-01
      • 2023-01-17
      • 2019-04-01
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多