I have a schema like so:
{
color: [
"red",
"yellow"
]
...
}
Any of the docs in the collection could have any number of colours (main seven by name).
In mongoose I try and find any documents that match, "red" or "blue" or "green" and return those documents that contain any of those three colours, I do not want to filter out other colours such as "yellow". I tried mongodb $in operator like so
model.find({ colors: { "$in": ["red", "blue", "green"] } })
.limit(50).exec((err, data) => {
if (err) throw err;
else console.log(data);
});
But, when I run this I am getting nothing in return even though there would be tonnes that have at least a colour of red, blue, or green.
Id like to get the documents where any of the documents color[] matches any of the comparisons color[].
EDIT:
I tried:
var colors = ["red", "blue"];
var obj = {};
obj.$match = { 'color': { '$in': colors } };
obj.$match = { 'color': { '$elemMatch': colors } };
obj.$match = { 'color.$': { '$in': colors } };
obj.$match = { 'color.*': { '$in': colors } };
obj = { colors: { $elemMatch: { $in: colors } } };
model.find(obj, ...);
And other combinations based off that post, but I am still getting nothing in return.
I basically want something like this:
var CheckIfAnyInArray = (obj) => {
obj.color.forEach((i) => {
if (colors.indexOf(i) > -1) return true;
};
return false;
};
EDIT: Solution...
So, I am an idiot, the problem is not my calls its a typo. The document schema is 'colors' not 'color'. I kept on overlooking the 's' and not realising it.
So this solution works:
model.find({ colors: { $in: colors } })...;
Very stupid mistake on my part.