How to run js file in mongo using spring data

你离开我真会死。 提交于 2019-11-29 07:02:43

Here's the relevant section of the reference docs on how to work with scripts in Spring Data MongoDB.

ScriptOperations scriptOps = template.scriptOps();

// Execute script directly
ExecutableMongoScript echoScript = new ExecutableMongoScript("function(x) { return x; }");
scriptOps.execute(echoScript, "directly execute script");     

// Register script and call it later
scriptOps.register(new NamedMongoScript("echo", echoScript)); 
scriptOps.call("echo", "execute script via name");    

What if you read text of your JavaScript from the file manually and put it into $eval? Something like:

    StringBuilder text = new StringBuilder();
    BufferedReader br = new BufferedReader(new FileReader(
            new File("/path/file.js")));
    try {
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            text.append(line).append("\n");
        }
    } finally {
        try { br.close(); } catch (Exception ignore) {}
    }
    BasicDBObject obj = new BasicDBObject();
    obj.append("$eval", text.toString());
    System.out.println(mongoTemplate.executeCommand(obj));

If it works then check that your file is accessible in server-side file system. Because load() is executed on server side.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!