0

I have an array of strings in my schema, and I'm trying to filter documents depending on their arrays containing certain strings or not. Below is my schema, where the ingredients array is what I'm trying to filter by:

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

In nodejs, I have the following inside my express router:

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);
  }
});

Here's an example request being sent:

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

I would expect to get all food documents where their ingredients array contain both Salmon Meal and Deboned Turkey, but I always get an empty array. The casing is correct. If I just use one ingredient in the query, it works fine.

0

2 Answers 2

1

Use $all

match.ingredients = { $all: req.query.ingredients };

https://docs.mongodb.com/manual/reference/operator/query/all/

Sign up to request clarification or add additional context in comments.

Comments

1

Use $in

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

3 Comments

That returns all food objects where either Salmon Meal or Deboned Turkey is an ingredient. OP asked for a way to get all food objects where both Salmon Meal AND Deboned Turkey are ingredients.
Vuza is correct, but your answer helps me with another task I was trying to complete. Thanks!
Glad I was still able to help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.