【问题标题】:How could I load other js scripts and run it with mongodb我如何加载其他 js 脚本并使用 mongodb 运行它
【发布时间】:2015-09-02 02:40:39
【问题描述】:

我需要写一堆查询。

每个查询都共享一些common data structurefunction

如何加载common.js 并在app.js 中使用functionconstants(实际上我是在咖啡中写的,然后将其转换为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)

【问题讨论】:

  • 实际的 JavaScript 是什么样的?您的lib-get-allergic-collections.js 中是否包含common.js 的翻译版本?我会先尝试将您的 JavaScript 代码加载到 mongo shell 以解决任何语法错误,或者在您的问题中包含实际的 leading_zero() 函数代码。引用错误表明您尚未加载定义 leading_zero() 函数的 JavaScript 文件。
  • 如何包含common.js?您在用户数组中存在语法错误(应以逗号分隔),但函数定义似乎没问题。也许您在app.js 的开头缺少像load("./lib/common.js") 这样的行?

标签: javascript mongodb coffeescript


【解决方案1】:

函数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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 2012-03-05
    相关资源
    最近更新 更多