Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

save javascript objects with functions in mongodb

save javascript objects with functions in mongodb

Problem

I am trying to save a javascript Object with functions,but facing an error. Here is the code:

var mongo = require('mongodb');
createObject = function(){
var data = {_id:1,"name":"object", 
   "fun":new mongo.Code("function fun() {print(1)}")};
   db.collection("objects").insert(data,function(err,result){   
    console.log(err);
    console.log(result);
   });
}

getObject = function(){
 var f = db.collection("objects").findOne();
 f.fun(); 
}

And the error :

    throw err;
          ^
TypeError: Object # has no method 'fun'

When I checked mongodb, it is saving "fun" function. But not executed when retrieved from mongo ?

Thanks in advance.

Problem courtesy of: codejammer

Solution

I haven't solved the problem with running the function, but i've noticed an error in the code, getObject should look like

getObject = function(){
 db.collection("objects").findOne(function(err, f) {
   console.log(f);
   // f.fun(); 
 });
}

You can extract the function as string and maybe use eval to run it if you really need it? I don't know (I haven't found) better answer.

Solution courtesy of: lopisan

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

save javascript objects with functions in mongodb

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×