如何查询 Mongoose 嵌套数据? (猫鼬/快递)

时间:2021-01-05 21:30:22

标签: javascript reactjs mongodb express mongoose

我想从我的猫鼬数据集合中查询项目数据。我只需要用户“456”项目“4”的“stocked”布尔值,但是当我在我的示例中查询时,我收到的是整个用户对象。

数据:

data = [{
    userId: "123",
    items: [{
        item: "2",
        stocked: false
      },
      {
        item: "3",
        stocked: true
      },
      {
        ...more items
      }
    ],
  },

  {
    userId: "456",
    items: [{
        item: "1",
        stocked: true
      },
      {
        item: "4",
        stocked: true
      },
      {
        ...more items
      }
    ],
  },

  {
    ...more users
  }
]

路线:

router.post("/example", (req, res) => {

  Data.findOne({
      userId: "456",
      "items.item": "4"
    }
  }).then((item) => {
  console.log(item) // desired: {item: "4", stocked: true}

  if (item.stocked) {
    console.log("Item is stocked!")
  }
})

})

问题:响应是包含所有项目的整个用户对象:

{
  userId: "456",
  items: [{
      item: "1",
      stocked: true
    },
    {
      item: "4",
      stocked: true
    },
    {
      ...more items
    }
  ],
},

想要的回复:{ item: "4", stocked: true }

任何提示或帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

使用聚合管道,您可以使用 $elemMatch 或 $unwind。

$elemMatch 运算符将查询结果中的字段内容限制为仅包含与 $elemMatch 条件匹配的第一个元素。

Data.aggregate([
 {$match: {userId: "456", "items.item": "4"}},
 {$project: { items: { $elemMatch: { "items.item": "4"} }}}
]);

$unwind 将返回所有符合条件的元素。

Data.aggregate([
 {$match: {userId: "456", "items.item": "4"}},
 {$unwind: "$items"},
 {$match: { "items.item": "4"} }
])
相关问题