我使用以下代码通过spring数据
在js中运行mongo脚本ScriptOperations scriptOps = mongoOperation.scriptOps();
// Execute script directly
ExecutableMongoScript echoScript = new ExecutableMongoScript("function(x) { return x; }");
Object ob=scriptOps.execute(echoScript, "directly execute script");
System.out.println(ob);
// Register script and call it later
scriptOps.register(new NamedMongoScript("runjs", "D:\\GSTR3\\gstr3b.1.a.js"));
scriptOps.call("runjs", "execute script via name");
“echoScript”运行但“runjs”出错:
Caused by: com.mongodb.CommandFailureException: { "serverUsed" : "/10.144.113.138:27017" , "ok" : 0.0 , "errmsg" : "ReferenceError: runjs is not defined :\n_funcs1@:1:24\n" , "code" : 139 , "codeName" : "JSInterpreterFailure"}
at com.mongodb.CommandResult.getException(CommandResult.java:71)
at com.mongodb.CommandResult.throwOnError(CommandResult.java:110)
at com.mongodb.DB.eval(DB.java:358)
at org.springframework.data.mongodb.core.DefaultScriptOperations$2.doInDB(DefaultScriptOperations.java:119)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:446)
... 2 more
但是如果我通常由node.js运行脚本,我得到结果:
D:\GSTR3>node gstr3b.1.a.js
{ Gstin: '27AIXPT3280A1Z2',
t_ival: 100003.78,
t_iamt: 0,
t_camt: 173520.1,
t_samt: 173527.69999999998,
t_itm_count: 33 }
D:\GSTR3>
答案 0 :(得分:0)
scriptOps.register将ExecutableMongoScript作为参数,语法:scriptOps.register(ExecutableMongoScript arg0)和NamedMongoScript采用两个参数,语法:NamedMongoScript(String name,ExecutableMongoScript script),它从不采用JavaScript路径。
因此,我们可以做的是将.js脚本作为java处理器运行并等待其完成并从其输入流中获取输出。
try{
String nodejsPath = "D:\\GSTR3\\gstr3b.1.a.js";
String cmd = "node " + nodejsPath;
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
} catch (InterruptedException ex) {
ex.printStackTrace();
}