如何从发送到 Mongo 的脚本返回值?
我有一组数据库管理任务需要在其他一些 rake 任务之后运行。所以我阅读了 Ruby Mongo 驱动程序源 和一些博客文章,我最终得到了这段代码:
scr = open("./scripts/update_stats.js", &:read)
db = Mongoid::Config::master
result = db.command({:$eval => scr})
logger.debug result
logger.warn "Finished updating stats"
在脚本中,我有几个函数,然后是最后一个:
r = update_stats();
print("update result:");
print (r);
好的,所以当我直接通过命令行运行它时,一切都运行良好。嗯,似乎是这样。但我想获取结果值并将其放入我的日志中。我想我可以将值存储到数据库中然后将其取出。看来应该有更好的办法。我从日志中得到的信息是:
DEBUG 2012-01-03 22:27:03 -0800 (21392) {"retval"=>nil, "ok"=>1.0}
除了它没有爆炸之外,这并没有告诉我太多信息。那么,如何获取 update_stats
的返回值并将其记录到我的 Ruby 代码中呢?
I have a set of database administration tasks that need to run after some other rake tasks. So I read the Ruby Mongo driver source and a few blog posts and I ended up with this code:
scr = open("./scripts/update_stats.js", &:read)
db = Mongoid::Config::master
result = db.command({:$eval => scr})
logger.debug result
logger.warn "Finished updating stats"
In the script I have several functions and then one final one:
r = update_stats();
print("update result:");
print (r);
Ok, so it's all running fine when I run it directly via the command line. Well, it seems to be. But I'd like to take the result value and stow it into my logs. I could store the value into the database and then pull it out I suppose. Seems like there should be a better way. What I do get it my logs is:
DEBUG 2012-01-03 22:27:03 -0800 (21392) {"retval"=>nil, "ok"=>1.0}
That doesn't tell me much other than that it didn't blow up. So, how can I get the returned value of update_stats
and log it in my Ruby code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,这里有两个潜在的问题。
第一个问题是您正在针对数据库运行 JS 文件,但我不太清楚这是如何工作的。看起来像是 Mongoid 的一些特殊功能?你期待什么结果?
第二个问题是,如果 rake 机器具有驱动程序访问权限,则根本不清楚为什么要使用 JS 文件。您运行的哪些命令不能直接通过 Ruby 驱动程序作为命令运行?
一般来说,唯一需要引入任意 JS 文件的时候是当您直接通过 mongo 程序调用作业时。因此,您可以从
cron
作业运行mongo my_map_reduce.js
,这是有意义的。如果您正在运行的命令可以通过驱动程序访问(99% 的情况都是如此)。然后用 Ruby 编写整个管理脚本。
OK, so there are two potential issues here.
The first issue is that you are running a JS file against the database, but I'm not really clear how this works. It looks like some special feature of Mongoid? What result are you expecting?
The second issue is that it's not clear why you're using a JS file at all if the rake machine has driver access. What commands are you running that cannot be simply run as commands via the Ruby driver directly?
In general, the only time you need to bring in an arbitrary JS file is when you're calling jobs directly via the
mongo
program. So you would runmongo my_map_reduce.js
from acron
job and this would make sense.If the commands you're running are accessible via the driver (this is true 99% of the time). Then just write the whole admin script in Ruby.