1

I'm trying to pass arguments into a mongo query - if I type the literal, it works fine, however, when I try to replace the literal with the variable (argument), it fails

imagine a data set with "things"

{"thing": {"name":"book","label":"Bobs"}}
{"thing": {"name":"blanket","label":"Bobs"},
{"thing": {"name":"books","label":"Jills"},
{"thing": {"name":"blankets","label":"Jills"},

I have a method to find "Book" "book" "Books" "books" or "blankets"

If I do this with the literal 'Book' - it works

function( name, callback ) {
    Catalog
        .find({ 'thing.name': {"$regex": /Book/, "$options": "i" }})
        .exec(callback);
}

However - I want the argument 'name' to be used.

function( name, callback ) {
    Catalog
        .find({ 'thing.name': {"$regex": /name/, "$options": "i" } })
        .exec(callback);
}

But this doesn't work, it appears to be looking for the literal 'name' not the passed in value. how to i escape this?

2 Answers 2

2

Could be done like this:-

function( name, callback ) {

    Catalog
        .find({ "thing.name": { $regex: name, $options: "i" }})
        .exec(callback);
}

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

Comments

1

Create an instance of RegExp class. It also allows you to remove $options property from the query, like below:

function( name, callback ) {

    var regexName = new RegExp(name, "i");
    Catalog
        .find({ 'thing.name': { "$regex": regexName } })
        .exec(callback);

}

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.