Liam Staskawicz avatar Liam Staskawicz committed 0588a94

* tweaks to and tests for db.eval()

Comments (0)

Files changed (2)

     return res
   }
   
-  Obj? eval(Str javascript, List args)
+  **
+  ** Evaluate a JavaScript snippet server-side.
+  ** This can be helpful when you want to reduce network bandwidth for low-touch operations.
+  ** If your javascript Str is a function that accepts arguments, they can be passed in
+  ** as the args parameter.
+  **
+  ** Mongo provides a server side JS api for finding/updating/deleting objects,
+  ** which is available to you in an eval script - 
+  ** see http://mongodb.onconfluence.com/display/DOCS/mongo+-+The+Interactive+Shell 
+  **
+  Obj? eval(Str javascript, List args := [,])
   {
-    cmd := ["\$eval": javascript, "args": args] { ordered = true}
+    cmd := [:] { ordered = true }
+    cmd["\$eval"] = javascript
+    if(!args.isEmpty) cmd["args"] = args
     doc := command(cmd)
-    if(!cmdOk(doc))
+    if(cmdOk(doc))
       return doc["retval"]
     else
       throw MongoOpErr("eval failed: ${doc}")
     db.repair(true, true) // just run it...make sure no Errs are thrown
   }
   
+  Void testEval()
+  {
+    verifyEq(3f, db.eval("function (x) {return x;}", [3]))
+    
+    verifyNull(db.eval("function (x) {db.test_eval.save({y:x});}", [5]))
+    verifyEq(5f, db["test_eval"].findOne()["y"])
+    
+    verifyEq(5f, db.eval("function (x, y) {return x + y;}", [2, 3]))
+    verifyEq(5f, db.eval("function () {return 5;}"))
+    verifyEq(5f, db.eval("2 + 3;"))
+    // 
+    // verifyEq(5f, db.eval(Code.new("2 + 3;"))
+    // verifyEq(2f, db.eval(Code.new("return i;", {"i" => 2}))
+    // verifyEq(5f, db.eval(Code.new("i + 3;", {"i" => 2}))
+    
+    verifyErr(MongoOpErr#) { db.eval("5 ++ 5;") }
+  }
+  
 }
 
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.