Dhanushka Dolapihilla
Dhanushka Dolapihilla

Reputation: 1145

Excluding quotes from a variable string for a mongodb query

I am a mongodb newbie, having said that; I am getting a user input string to perform a "Does Not Contain" mongo query.

And this regex with a "$not" ought to do it as I know.

db.collection.find( { item: { $not: /STRING GOES HERE/ } } ) 

But the thing is, since I make up the query with string concatenation the query looks like this (with a double quoted regex.) i.e.

db.collection.find( { "item": { "$not": "/theString/" } } )

When i try it with robomongo I get

error: {
    "$err" : "Can't canonicalize query: BadValue $not needs a regex or a document",
    "code" : 17287
} 

When I manually exclude the double quotes surrounding the regex I get the expected output.

I dont know if I am overcomplicating this with too much information, Please tell me how do I get this done? Simply, How do I exclude the double quotes surrounding the regex using Javascript ; or is there any other way to get this done.

Edit : I am using nodejs and mongoose for this.

Upvotes: 1

Views: 3067

Answers (2)

Heshan Perera
Heshan Perera

Reputation: 4630

One way around this is, try not to use string concatenation.

In your Javascript that calls on Mongoose, create a Javascript object as the query and append to its prototype as follows...

var query = {};
query.Item = {$not : "theString"};

Pass this to your Mongoose model.

For example,

youMongooseModel.find(query, function(err, result){});

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 312055

When creating a regex from a string you need to use the RegExp constructor:

var str = 'theString';
db.collection.find( { "item": { "$not": new RegExp(str) } } )

Upvotes: 3

Related Questions