1

I need to find out that if it is possible to use function in $where clause string like this:

db.myCollection.find( "this.name == 'xyz' || function() {return 1>0;} || this.name == 'abc'" );

Thanks in advance.

Akdeniz
  • 1,260
  • 11
  • 21

2 Answers2

3

I'm not quite sure what you're trying to do, but put all your checks in a single function that's the value of the $where:

db.myCollection.find({$where: function() {
    return this.name == 'xyz' || 1>0 || this.name == 'abc';
}});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Yes, I know right approach but I just need to know that if simple conditions and more complex functions can be combined in a string for $where clause. – Akdeniz Apr 07 '14 at 17:43
  • @Akdeniz Maybe I'm missing something, but can't you just try what you're looking to do and see if it works? I don't expect it will. – JohnnyHK Apr 07 '14 at 18:02
  • Actually I tried that and expected to get all myCollection data to return but on the contrary it returned nothing. At this point I don't know which one is the case: - it is possible to use function in string but im using improperly or - such usage is not possible and somehow function breaks the overall condition. btw thx for your time.. – Akdeniz Apr 07 '14 at 19:48
  • @Akdeniz theoretically it should work so long as it all runs within a evable statement like that but there could be some complication to its usage, I have never tried it. – Sammaye Apr 08 '14 at 07:11
-1

It is possible to use nested functions within functions in JS but there are some considerations as this question will tell you: JavaScript Nested function

However, as @JohnnyHK said, this isn't really a good way of doing a $where, if there is at all.

Community
  • 1
  • 1
Sammaye
  • 43,242
  • 7
  • 104
  • 146