3

Using Mongoose, trying to query all records that do not contain a substring.

I have a User Schema, with an email field. I want get all user documents where the email field does not contain @testschool.edu . Reg Ex seems to be not working.

Tried this:

User.count()
    .where({email: { "$regex": '^((?!testschoo.edu).)*$', "$options": "i" }})

2 Answers2

1

This actually works... just didn't have the right string. Thanks for pointing it out - Neil Lunn

1

Another possible solution would be using the logical query operator $not:

return User.find(
    { email: {$not: /.*testschool\.edu.*/} },
    {}).fetch()

If you want to "blacklist" multiple substring patterns, you could use the logical query operator $nor, which supports RegEx as well (not explicitly mentioned by the offical docs):

return User.find(
    { $nor: [{email: /.*testschool\.edu.*/}, {email: /.*catholicschool\.edu.*/] },
    {}).fetch()

Of course, in this particular case we know that nothing should come after the substring, so we could be more precise searching for /.*testschool\.edu$/

For a detailed explanations why the solution in the question works, see this excellent answer.

anarchist912
  • 797
  • 8
  • 17