Mongoose: how to call my functions

49 views Asked by At

I'm unable to call the calc function. Why?

MyModel.find(
{
    $where: function() {
        return calc(this) > 500;
    }
},
function (err, results) {
  if (err) return console.error(err);
  console.log(results);
});

function calc(obj) {
    return obj.x + obj.y;
}
1

There are 1 answers

0
JohnnyHK On

The code of the $where is sent to the server for execution, so it can only reference functions within its own scope (as well as the built-in function listed here).

So your code would have to be restructured with calc defined in scope:

MyModel.find(
{
    $where: function() {
        function calc(obj) {
            return obj.x + obj.y;
        }
        return calc(this) > 500;
    }
},
function (err, results) {
    if (err) return console.error(err);
    console.log(results);
});