Mongoose: special chars break $regex query

Created on 25 Jan 2016  路  11Comments  路  Source: Automattic/mongoose

I tried this query:

mymodel.find({
        content:{'$regex': 'ello [pos'}
    })

It doesn't match this document

{ 
    "_id" : ObjectId("56a6192d8903f7dc101d782d"), 
    "content" : "hello [post]", 
    "__v" : NumberInt(0)
}

the special char "[" break the query, there is a better method to accomplish a query "LIKE" (sql speaking)?

can't reproduce

Most helpful comment

I found this on stackoverflow

query.replace(/[-[\]{}()*+?.,\\/^$|#\s]/g, "\\$&");

maybe there is no need of a module, or the module is more safe somehow?

All 11 comments

Just use the escape-regexp module or something similar to escape the user input before putting it into a query.

I found this on stackoverflow

query.replace(/[-[\]{}()*+?.,\\/^$|#\s]/g, "\\$&");

maybe there is no need of a module, or the module is more safe somehow?

The module is pretty much the same thing: https://github.com/component/escape-regexp/blob/master/index.js .

Sorry I reopen, I've just noticed this code doesn't work if I have special char in the user name in the db ( "Micke[y] mouse"). The query returns nothing.

app.get('/api/community/users', function(req,res) {
    var q= (req.query.q) ?
            escape(req.query.q):
            '.*';
    com_user.find({name:{$regex: q}}, function(err,data){
        res.json(data);

    });
});

@alfredopacino the below script executes without error for me. What does your regexp look like?

'use strict';

var assert = require('assert');
var mongoose = require('mongoose');
var escapere = require('escape-regexp');

mongoose.connect('mongodb://localhost:27017/gh3796');

var PostSchema = mongoose.Schema({
  content: String
});

var Child = mongoose.model('Child', PostSchema);

Child.create({ content: 'Micke[y] mouse' }, function(error, doc) {
  Child.findOne({ content: new RegExp(escapere('Micke[y')) }, function(error, doc) {
    assert.ok(doc);
    process.exit(0);
  });
});

Issue's been stale for a while, closing.

sorry I can't reproduce myself neither.
Maybe the mistake was somewhere else :+1: .

hi @vkarpov15, sorry for reopen the issue but i have a question, for example,

i want to search the name "B&B H么tel" that contains special caraters like & and 么 by just typing "BB Hotel"

how can i do that ?

@askri2pac read up on mongodb collations

This saved my day:
$regex: new RegExp('^' + name.replace(/[-\/\^$*+?.()|[]{}]/g, '\$&') + '$', 'i')
This work with mongoose aggregate $match also. Check this out.

I found this on stackoverflow

query.replace(/[-[\]{}()*+?.,\\/^$|#\s]/g, "\\$&");

maybe there is no need of a module, or the module is more safe somehow?

this solved it for me

Was this page helpful?
0 / 5 - 0 ratings