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 #
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.