首页 > 解决方案 > 按数组中的对象过滤文档

问题描述

我的架构中有一个字符串数组,我试图根据它们的数组是否包含某些字符串来过滤文档。下面是我的架构,其中成分数组是我要过滤的内容:

const foodSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  ingredients: [
    {
      type: String,
      required: true,
      trim: true,
    },
  ],
});

在 nodejs 中,我的快速路由器中有以下内容:

router.get('/food', auth, async (req, res) => {
  const match = {};

  if (req.query.name) {
    match.name = req.query.name;
  }

  if (req.query.ingredients) {
    match.ingredients = req.query.ingredients;
  }

  try {
    const allFood = await Food.find(match);
    res.send({
      allFood,
    });
  } catch (error) {
    res.status(400).send(error);
  }
});

这是发送的示例请求:

{{url}}/food?ingredients=Salmon Meal&ingredients=Deboned Turkey

我希望获得所有食品文件,其中他们的成分数组包含三文鱼粉和去骨火鸡,但我总是得到一个空数组。外壳是正确的。如果我只在查询中使用一种成分,它就可以正常工作。

标签: node.jsmongodbexpressmongoose

解决方案


利用$in

if (req.query.ingredients && req.query.ingredients.length > 0) {
  match.ingredients = { $in: req.query.ingredients };
}

推荐阅读