简体   繁体   中英

How to find mongoose documents based on a string match on an array of substrings

Say I have an array of substring search parameters, like this:

const subStrings = ["foo", "bar", "baz", "whatever"];

I have to find all documents where a field of type string contains one or more of the provided substrings.

So if I have a schema like this:

const sampleSchema = new mongoose.Schema({
  fieldOne: {
    type: String,
    ...
  }
});

const Sample = mongoose.model('Sample', sampleSchema);

I've seen this operation in other questions:

    Sample.find ({
         fieldOne: { $regex: substrings, $options: 'i' }
    })

But I've only seen it work if substrings is of type string, and not an array of strings.

Can this still be done with a modified regex, or is there a better way?

you could use a pipe-delimited regex pattern with the keywords list like this:

const subStrings = ["foo", "bar", "baz", "whatever"];
const regex = subStrings.join("|");


 Sample.find ({
   fieldOne: { $regex: regex, $options: 'i' }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM