1

I have a schema that has some properties and array of objects as one of the properties, like that:

const Project = mongoose.Schema({
  _id: String,
  name: String,
  comments:[String]
  date: Date,
  tests:[{
          description: String,
          comments:[String]
        }]
});

i want to be able to filter all documents that contains some string.

The query should be searching for the string inside the 'name' field of 'Project' schema and inside the tests objects in their description field. and return all the documents that contains the string (in project name or in one of his test description)

1.what query should I use to do so?

2.same question but with filtering both schema and tests comments field in addition to description

Jon
  • 151
  • 1
  • 9
  • 2
    Possible duplicate https://stackoverflow.com/questions/31859800/how-to-search-for-text-or-expression-in-multiple-fields – chridam Aug 27 '20 at 15:25

1 Answers1

0
Project.find({ $or: [ {name: 'something'}, {comments: 'something'}, {'tests.description': 'something' }, {'tests.comments': 'something'} ] })

Let me know if this works for you.

Pritthish Nath
  • 134
  • 1
  • 8
  • Thanks but for some reason it does not work for me. What does work is the use of regex: Project.find({$or:[{"tests.description": { "$regex": req.params.filterStr}}, {"name": { "$regex": req.params.filterStr}},{"comments": { "$regex": req.params.filterStr}}]} – Jon Aug 30 '20 at 06:25
  • Yeah, regex will match the docs irrespective of exact matching. Without regex it will be return the docs which contains an exact match of the given string, no extra letter. But concept is same. – Pritthish Nath Aug 30 '20 at 14:40