The following code snippet:
var mongo = require('mongodb'); var db = new mongo.Db('test', new mongo.Server('127.0.0.1', 27017, {})); var callback = function (e, result) { if (e) { console.log(e); process.exit(1); } console.log(result); process.exit(0); } db.open(function (e) { if (e) callback(e); db.collection('system.js', function (e, coll) { if (e) callback(e); coll.save({ "_id" : "myFunction", "value" : "function myFunction() { return 123; }" }, function (e) { if (e) callback(e); db.eval("myFunction()", [], function (e, result) { if (e) callback(e); callback(undefined, result); }); }); }); });
outputs:
[Error: eval failed: invoke failed: JS Error: TypeError: myFunction is not a function nofile_a:0]
I found out that the problem is with quotation marks ("") that wrap the function definition.
In mongo-kli:
> db.system.js.find() { "_id" : "myFunction", "value" : "function myFunction() { return 123; }" }
But after:
> db.system.js.save({_id : "myFunction", value : function myFunction() { return 123; }});
and
> db.system.js.find() { "_id" : "myFunction", "value" : function cf__5__f_myFunction() { return 123; } }
db.eval ("myFunction ()") works!
So my question is: how to save a stored procedure from node.js using the native node-Mongodb driver?
source share