猫鼬:如何调用我的函数

时间:2015-06-10 00:02:44

标签: mongodb mongoose

我无法调用calc函数。为什么呢?

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 个答案:

答案 0 :(得分:0)

$where的代码被发送到服务器执行,因此它只能引用自己范围内的函数(以及列出的内置函数here)。

因此,您的代码必须使用范围中定义的calc重新构建:

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);
});