Search code examples
mongodbsails.jssails-mongo

Mongo query with regex fails when backslash\newline are present


I'm using MongoDB with Sails.

db.post.find( { body:  {"$regex" : /^.*twitter.*$/i }}).

This query is supposed to find only posts which contain 'twitter' in their body-field. For some reason it won't find a match if a backslash is present in the field (like a newline).

Is this known? What can I do about it?

Here are two examples to showcase the problem:

This document is returned by the find-command above:

{ 
    "_id" : ObjectId("54e0d7eac2280519ac14cfda"), 
    "title" : "Cool Post", 
    "body" : "Twitter Twitter twitter twittor"
}

This document is not returned by the find-command above:

{ 
    "_id" : ObjectId("54e0d7eac2280519ac14cfdb"), 
    "title" : "Cool Post with Linebreaks", 
    "body" : "This is a cool post with Twitter mentioned into it \n Foo bar"
}

Solution

  • Is this known?

    No. Its not an issue with the MongoDb search Engine.

    What can I do about it?

    You could change your Regular Expression to:

    var regex = new RegExp("twitter","i");
    db.posts.find( { body:  regex});
    

    The problem with your code is the decimal point .

    According to the doc,

    .

    (The decimal point) matches any single character except the newline character.

    which is why the string with a newline character is not taken to be a match.