Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save a stored javascript into mongodb from node.js

The following piece of code:

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 related to the quotes ("") wrapping the function definition.

On mongo-cli:

> 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;  
} }

the db.eval("myFunction()"), works!

So, my question is: How can I save a stored procedure from node.js using the node-mongodb-native driver?

like image 398
vdeantoni Avatar asked Apr 18 '12 14:04

vdeantoni


1 Answers

After reading the documentation about the driver data types, I realized that instead of passing the string with the code, I needed to pass a mongo.Code object:

{
  "_id" : "myFunction",
  "value" : new mongo.Code("function myFunction() { return 123; }")
}
like image 189
vdeantoni Avatar answered Oct 19 '22 22:10

vdeantoni