Storing a Javascript function in a mongoDB database for retrieval later.

421 views
Skip to first unread message

Adam Griffiths

unread,
May 9, 2016, 3:44:28 AM5/9/16
to mongodb-user
Hi,

I am using the Node.js driver for MongoDB.

I want to know if there is a way to store a function in a mongodb database, retrieve it later and then run it from within the node.js script. Currently I've been trying the below: 

var mongo = require("mongodb").MongoClient;

mongo
.connect("mongodb://localhost:27017/testdb", function(err, db){

   
var printHelloWorld = function(){
        console
.log("Hello World!");
   
}

   
var testData = {_id: "testData", data: printHelloWorld};

    db
.collection("test").insertOne(testData, function(err, result){

        console
.log("added data");

        db
.collection("test").find({_id: "test data"}).toArray(function(err, docs){
            docs[0].printHelloWorld();

       
});
   });

       

});

If I try to run this I get the following error:

TypeError: Cannot read property 'printHelloWorld' of undefined
    at /home/ubuntu/workspace/test2.js:16:20
    at handleCallback (/home/ubuntu/workspace/node_modules/mongodb/lib/utils.js:96:12)
    at /home/ubuntu/workspace/node_modules/mongodb/lib/cursor.js:835:16
    at handleCallback (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:159:5)
    at setCursorNotified (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:490:3)
    at /home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:561:16
    at queryCallback (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:241:5)
    at Callbacks.emit (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
    at null.messageHandler (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:295:23)
    at Socket.<anonymous> (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:285:22)


What can I do differently to store a function, or is it not possible?

Rhys Campbell

unread,
May 9, 2016, 5:11:48 AM5/9/16
to mongodb-user
You can although MongoDB don't seem very keen to encourage it...



Adam Griffiths

unread,
May 9, 2016, 5:21:59 AM5/9/16
to mongodb-user


On Monday, 9 May 2016 10:11:48 UTC+1, Rhys Campbell wrote:
You can although MongoDB don't seem very keen to encourage it...


I've already looked at this but it doesn't seem to work either, if I perform an identical operation but change the collection to system.js then I get the same error. 

If I pull code straight from the example in the page you linked and run it I instead get the following error

TypeError: Cannot read property 'js' of undefined
    at /home/ubuntu/workspace/test2.js:5:14
    at /home/ubuntu/workspace/node_modules/mongodb/lib/mongo_client.js:519:11
    at nextTickCallbackWith0Args (node.js:420:9)
    at process._tickCallback (node.js:349:13)

 

Adam Griffiths

unread,
May 9, 2016, 5:39:24 AM5/9/16
to mongodb-user


On Monday, 9 May 2016 10:11:48 UTC+1, Rhys Campbell wrote:
You can although MongoDB don't seem very keen to encourage it...


Also this example seems to be only for running functions within the MongoDB server itself, but I am looking to retrieve functions and then run them in node.js instead. 

Adam Griffiths

unread,
May 9, 2016, 8:24:20 AM5/9/16
to mongodb-user
After some more digging I have found this class that allows you to simply convert a function to a code object and that can be stored into the database.

After retrieval is there a way to easily convert from the code object back to a function that can be run?   

Wan Bachtiar

unread,
May 12, 2016, 2:08:33 AM5/12/16
to mongodb-user

I am looking to retrieve functions and then run them in node.js instead.

After retrieval is there a way to easily convert from the code object back to a function that can be run?

Hi Adam,

Generally, it is not recommended to dynamically evaluate code at runtime as it could be a potential security risk and performance issue.

Although if you have a good use case for it, you could store the function string into the database and construct later using Function() class. Using your code example:

var testData = {_id: "testData", data: "console.log('Hello World')"};

db.collection("test").insertOne(testData, function(err, result){
    console.log("added data");
    db.collection("test").findOne({_id: "testData"}, function(err, doc){
        func = new Function(doc.data);
        func();
    });
});

Please see Function constructor to find out more.

You may also be interested to know that the next session for free online course M101JS: MongoDB for Node.js Developers is starting in 24th May.

Best regards,

Wan.

Reply all
Reply to author
Forward
0 new messages