Query Mongoose Documents Based on Object Properties
10,280
You can use $in
to match against an array of values, and dot notation to target the text
field within each element of the tags
array. Any match will cause a doc to be included in the results.
var tagTexts = ['tall', 'small', 'green', 'blue'];
User.find({'tags.text': {$in: tagTexts}}, function(err, users) {...});
Author by
bipvanwinkle
Updated on June 09, 2022Comments
-
bipvanwinkle almost 2 years
I have the following Mongoose Schema:
var UserSchema = new Schema({ name: String, age: Number, ... tags: [{ text: String, ... }] });
and the following array:
var tagTexts = ['tall', 'small', 'green', 'blue'];
I would like to retrieve all user documents that contain at least one tag with a text property found within tagTexts.
For example, if I had the following users and tagTexts array
[{ name: 'Bob', age: 17, ... tags: [{ text: 'small', ... }] }, { name: 'Bill', age: 29, ... tags: [{ text: 'dandelion', ... }, { text: 'oak', ... }] }] var tagTexts = ['tall', 'small', 'green', 'blue'];
then Bob would be retrieved, but not Bill.
-
bipvanwinkle almost 9 yearsThank you. I had tried this before but I was using the wrong syntax so it wasn't working. I have updated my query to reflect your suggestion and I am getting the results I wanted. Thank you, thank you, thank you!
-
pedrotp about 8 yearsis this a good way to organize data in the schema or would it be inefficient for searching through a large amount of users/tags?
-
Ikdemm almost 3 yearsThank you for the answer. Worked like a charm!