最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

通过对象数组中的值查找

运维笔记admin11浏览0评论

通过对象数组中的值查找

通过对象数组中的值查找

我无法查询特定部门中包含的所有配置文件。

我正在使用带有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找到。

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论