在sails中使用mongodb的mapReduce, 出现错误 ReferenceError: root is not defined

起因

sails 中的 collection.mapReduce, scope定义为

1
2
3
4
scope = {
'其它方法': '其它方法',
getZeroDay: UtilitiesService.getZeroDay,
};

其中调用了 service 中定义的方法 getZeroDay
在 sails0.10 中使用没有问题, 但是更新到sails0.12后出现了 ReferenceError: root is not defined

探索

在 UtilitiesService 定义了

1
2
3
4
5
6
7
8
function getZeroDay() {

}

global.getZeroDay = getZeroDay;
module.exports = {
getZeroDay: getZeroDay,
};

在其它地方调用如下内容

1
2
console.log(global.getZeroDay === UtilitiesService.getZeroDay); 
console.log(UtilitiesService.getZeroDay.toString());

结果却是 UtilitiesService.getZeroDay 被转换了

从sails的源码中得知, sails0.12版本对 loadService 多出了 bindToSails, 而 bindToSails 调用了 _.bindAll, 最后输出了如上图所示的内容

sails0.10

sails0.10

sails0.12

sails0.12

解决方案

collection.mapReducescope 不要从 service 中获取



文章若有纰漏请大家补充指正,谢谢~~
http://blog.xinshangshangxin.com SHANG殇