Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Mongoose Documents Based on Object Properties

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.

like image 649
bipvanwinkle Avatar asked Dec 25 '22 18:12

bipvanwinkle


1 Answers

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) {...});
like image 70
JohnnyHK Avatar answered Jan 06 '23 11:01

JohnnyHK