I hold recipes in a database, each recipe has ingredients field of type Array. to the query i pass an array of ingredients for example:
["banana", "apple", "watermelon"] , and i want to find all recipes in the db containing in the ingredients field each of the ingredients passed to the query. the issue is the ingredients passed to the query are usually substrings of the ingredients in the DB, so for example a document in the DB can have "1 ripe banana" in its ingredients array and in the query i pass "banana" , which mean this document should be returned has a result. the result documents should include each of the ingredients passed.
i did manage to find all recipes including at least one using this code:
app.get('/recipe', (req, res) => {
if (req.query.ingredients) {
let ingredientMap = req.query.ingredients.map(x =>
Recipe.find({ingredients: {$regex: new RegExp(JSON.parse(x).name)}}));
return Promise.all(ingredientMap).then((results) => {
if (!results) {
res.status(404).send();
}
let filteredResults = results.filter(x => {
return typeof x !== 'undefined' ? x[0] : null
});
let merged = [].concat.apply([], filteredResults);
res.status(200).send(merged);
}).catch( e => {
res.status(400).send();
})
}
});
but how can i make a query where each result includes all of the ingredients passed to the query, as substrings?
.nameof an ingredient is a plain string, right? Odd, it looks like you're doing it exactly as you should be"banana"for example, which means array of strings$allsince the issue is he wants substrings.$allwould have worked if his recipes ware composed of "clean" ingredients but he has1 awesome bag of bananasand he searches forbanana. Hence the need for the$regexetc.