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.

4

1 回答 1

1

我还没有解决运行函数的问题,但我注意到代码中有一个错误,getObject应该看起来像

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

您可以将函数提取为字符串,eval如果您真的需要它,也许可以使用它来运行它?我不知道(我还没有找到)更好的答案。

于 2013-04-18T11:52:51.023 回答