techniques for storing libraries in mongoDB's

2019-08-28 02:21发布

Are there any reliable techniques for storing prototype-based libraries/frameworks in mongoDB's system.js? I came across this issue when trying to use dateJS formats within a map-reduce. JIRA #SERVER-770 explains that objects' closures - including their prototypes - are lost when serialized to the system.js collection, and that this is the expected behavior. Unfortunately, this excludes a lot of great frameworks such as dojo, Google Closure, and jQuery.

Is there a way to somehow convert or contain libraries such that they don't rely on prototyping? There's some promise to initializing before the Map-Reduce and passing them in through the scope object, but I haven't had much luck so far. If my approach is flawed, what is a better way to enable server-side javascript re-use for mongo?

1条回答
欢心
2楼-- · 2019-08-28 03:01

Every query using JS may reuse or get a brand new JS context, on which stored JS objects are loaded. In order to do what you want, you need either:

  1. mongod to run the stored code automatically when installing it
  2. mapreduce to have an init method

The first is definitely the more interesting feature. Turns out that mongodb v8 build automatically does it (but not officially supported), but not the official spidermonkey build.

Say you store code like:

db.system.js.save({ _id: "mylib", value: "myprint = function() { print('installed'); return 'installed';" }

Then in v8 you can use myprint() freely in your code, but with SM you would need to call mylib() explicitly.

As a workaround you can create another method:

db.system.js.save({ _id: "installLib", value: "if (!libLoaded) mylib(); libLoaded = true;" }

And call it from your map() function.

Created ticket in order to standardize engines and allow automatic run: https://jira.mongodb.org/browse/SERVER-4450

查看更多
登录 后发表回答