我需要编写一堆查询。
每个查询都共享一些通用数据结构
或函数
我如何加载common.js
并使用app.js
中的函数
和常量
( actullay我是用coffee写的,然后转成js
)
我收到错误 mongo localhost:27017/test app.js
E QUERY ReferenceError: leading_zero is not defined
common.js
USERS = [
'477 ',
'4770 '
]
leading_zero = function(num, size) {
var s;
if (size == null) {
size = 2;
}
s = num + '';
while (s.length < size) {
s = '0' + s;
}
return s;
};
app.js
load("./common.js")
print(leading_zero(3))
print(USERS)
最佳答案
函数leading_zero需要位于您的数据库上。引用http://docs.mongodb.org/manual/tutorial/store-javascript-function-on-server/ 。
首先在 shell 上运行:
db.system.js.save(
{
_id: "leading_zero",
value : function(num, size) {
var s;
if (size == null) {
size = 2;
}
s = num + '';
while (s.length < size) {
s = '0' + s;
}
return s;
}
}
)
这会将函数作为系统函数保存在数据库上。
运行db.loadServerScripts();在 shell 上一次加载所有脚本。
然后您可以在查询中的任何位置调用它。
print(leading_zero(3)) // directly on shell
db.myCollection.find( { $where: "this.credits == myfunc(this.xValue)" } ); // on query
关于javascript - 我如何加载其他js脚本并使用mongodb运行它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30881810/