Mongodb 如何在mapreduce中检测错误
让我们创建一个“error_test.js”文件,其中包含:Mongodb 如何在mapreduce中检测错误,mongodb,Mongodb,让我们创建一个“error_test.js”文件,其中包含: db = db.getMongo().getDB( "mydb" ); db.mycol.insert( { hello : "world" } ); print("it is shown"); db.runCommand( { mapReduce: "mycol", map: function(){ print(no
db = db.getMongo().getDB( "mydb" );
db.mycol.insert( { hello : "world" } );
print("it is shown");
db.runCommand(
{
mapReduce: "mycol",
map: function(){ print(not_exists); },
reduce: function(key, values){},
out: { replace: "myrescol" }
}
);
print("it is shown too (after error in mapreduce!)");
如果运行该文件(在Windows命令行中),我将获得:
因此我们可以推断:
- mapreduce错误不会停止执行
- mapreduce错误不会显示给用户
- mapreduce错误不会转换为退出代码(0=成功)(因此调用程序无法检测到错误)
谢谢您需要将返回文档从
db.runCommand()
捕获到一个变量中,然后在脚本中检查其ok
值-然后可以抛出错误或打印输出等
print("it is shown");
var res = db.runCommand(
{
mapReduce: "mycol",
map: function(){ print(not_exists); },
reduce: function(key, values){},
out: { replace: "myrescol" }
}
);
printjson(res);
if (res.ok == 0) {
print("Oopsy!");
throw("error! " + res.errmsg + " returned from mapreduce");
}
print("it is shown too (after error in mapreduce!)");
您可以将其放入try-catch块中,或者在检测到错误后执行任何您想要的操作-包括返回一些错误代码…谢谢,它可以工作。我不知道“db.runCommand()”会返回一个值(json文档)。事实上,我看到在手册的以下几页中没有提到返回值:1)db.runCommand():2)mongo Shell方法:也许在其他几页中有提到,但我没有找到它们。如果某个mongo web编辑器正在阅读此评论,请在这些页面中添加有关返回值的信息。非常感谢。
Wed Jun 12 10:02:37.393 [conn14] JavaScript execution failed: ReferenceError: not_exists is not defined near '(){ print(not_exists)'
print("it is shown");
var res = db.runCommand(
{
mapReduce: "mycol",
map: function(){ print(not_exists); },
reduce: function(key, values){},
out: { replace: "myrescol" }
}
);
printjson(res);
if (res.ok == 0) {
print("Oopsy!");
throw("error! " + res.errmsg + " returned from mapreduce");
}
print("it is shown too (after error in mapreduce!)");