1

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 #<Object> has no method 'fun'

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

Thanks in advance.

codejammer
  • 469
  • 1
  • 7
  • 18
  • I tried this [link](http://stackoverflow.com/questions/10211076/how-can-i-save-a-stored-javascript-into-mongodb-from-node-js) as well but didn't help – codejammer Apr 18 '13 at 11:00
  • I just tried to run it in mongodb shell and it worked.. – lopisan Apr 18 '13 at 11:01
  • @lopisan Yes, this is working in mongo shell but not I am trying to execute it in node.js and its not working – codejammer Apr 18 '13 at 11:04

1 Answers1

1

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.

lopisan
  • 7,720
  • 3
  • 37
  • 45