Roderick Obrist
Roderick Obrist

Reputation: 3828

MongoDB: using $where in find() throws error

Surprised this hasn't been asked yet (well I can't find it), but lets say I am using the query:

db.find('this.CustomerPurchaseOrderNumber.indexOf("value") !== -1')

3/4s of my data has CustomerPurchaseOrderNumber as a string, but some of them have it as null, resulting in this error:

error: {
    "$err" : "TypeError: Cannot call method 'indexOf' of null near 'value\") !== -1' ",
    "code" : 16722
}
  1. I must use a "javascript function" as a query
  2. I have no control over the data

My question is, is it possible to pass some sort of "throwIsFalse" flag which means that whenever that function throws an error, the row is not matched?

Thanks guys

Upvotes: 0

Views: 131

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

You shouldn't be using a $where query for that as you can do it more efficiently (and without the problem you're hitting) as:

db.find({CustomerPurchaseOrderNumber: "value"})

But if you need to use a $where query for some reason, you would just need to check that CustomerPurchaseOrderNumber actually exists before calling indexOf on it:

db.find('this.CustomerPurchaseOrderNumber && this.CustomerPurchaseOrderNumber.indexOf("value") !== -1')

Upvotes: 1

Related Questions