综合编程

save javascript objects with functions in mongodb

微信扫一扫,分享到朋友圈

save javascript objects with functions in mongodb
0 0

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.

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

Node.js Recipes
感谢您的支持!

    Don’t sleep on Latin America, game publishers

    上一篇

    Apache Log4j 2.11.2 发布,流行的 Java 日志组件

    下一篇

    您也可能喜欢

    评论已经被关闭。

    插入图片

    热门分类