Case-insensitive mongoose.model.find

5,183 views
Skip to first unread message

John Ervin

unread,
Aug 18, 2016, 12:03:25 PM8/18/16
to Mongoose Node.JS ODM
Hi There,

I understand we can use regex to make case insensitive find off of a string with the 'i' option. (i.e. mongoose.model.find({ username : /^user/i }, callback ).

Yet how does one do such a thing when instead of a the regex we have a variable?  Of course though we could ensure case insensitivity at database entry and pattern matching, that would be undesirable.

thank you,
John 

John Ervin

unread,
Aug 18, 2016, 12:43:00 PM8/18/16
to Mongoose Node.JS ODM
Think I've got it. Trick is to use the mongoose query helpers to build the regexp for the query:


user_schema.query.by_username = function(username) {
  return this.find({ username: new RegExp('\\b' + username + '\\b', 'i') });
};

Need the word boundaries to ensure only whole word matches. 

John

Jeff Cunningham

unread,
Jan 7, 2019, 9:14:35 PM1/7/19
to Mongoose Node.JS ODM
This was very helpful to me. Where are these "Mongoose Query Helpers" you speak of, is this a tool somewhere? Didn't see it in the Mongoose documentation.
Reply all
Reply to author
Forward
0 new messages