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

From: Adam Griffiths <adamfrederickgriffiths@xxxxxxxxx>
To: mongodb-user <mongodb-user@xxxxxxxxxxxxxxxx>
Date: Mon, 9 May 2016 00:06:35 -0700 (PDT)
Why ads?
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?

-- 
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.

For other MongoDB technical support options, see: https://docs.mongodb.org/manual/support/
--- 
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user+unsubscribe@xxxxxxxxxxxxxxxx.
To post to this group, send email to mongodb-user@xxxxxxxxxxxxxxxx.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/04d7a273-c304-484d-a72f-b691da6cda38%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Why ads?