7

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?

1 Answer 1

15

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; }")
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.