1

I've created a client side mongodb interface to talk to server side mongodb.
it's very similar to the mini-mongo implemented in the meteor. here is an example:

model.find({"field": /search/}).exec(function(err, model){
    construct(model);
});

now normally everything works fine except when I use the regex. and I know what's the problem but I cannot fix it.
the problem, as you have guessed it, is when the regex /regexParameter/ when sent by ajax to server, is converted to "/regexParameter/" and the single quotes(or double) make the regex a normal string.
in the server I have something like this:

var findObject = req.query.findObject // {"field": "/search/"} :(
req.models[config.table]
   .find(findObject)
   .exec(function(err, model){
        return res.json({
            error: err,
            result: model,
        });
   });

is there anything I can do to make this work without writing like 100 of lines of code that iterates through each of the findObject and matches every string for a regex...?
Thanks everyone

1 Answer 1

2

You are right - you cannot pass RegExp objects between client and server because during serialization they are converted to strings.

Solution? (or perhaps - a workaround)

Use $regex operator in your queries, so you don't need to use RegExp objects.

So this:

{
  field: /search/
}

Becomes this:

{
  field: {
    $regex: 'search'
  }
}

Or, giving a case-insensitive search example:

{
  field: {
    $regex: 'search',
    $options: 'i'
  }
}

(instead of field: /search/i)

Read more about $regex syntax here (including about some of its restrictions).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.