【问题标题】:How can I save a stored javascript into mongodb from node.js如何将存储的 javascript 从 node.js 保存到 mongodb
【发布时间】:2012-04-18 14:04:43
【问题描述】:

以下代码:

var mongo = require('mongodb');

var db = new mongo.Db('test', new mongo.Server('127.0.0.1', 27017, {}));

var callback = function (e, result) {
if (e) {
    console.log(e);
    process.exit(1);
}

console.log(result);
process.exit(0);
}

db.open(function (e) {
if (e)  callback(e);

db.collection('system.js', function (e, coll) {
    if (e)  callback(e);

    coll.save({
        "_id" : "myFunction",
        "value" : "function myFunction() { return 123; }"
    }, function (e) {
        if (e)  callback(e);

        db.eval("myFunction()", [], function (e, result) {
            if (e)  callback(e);

            callback(undefined, result);
        });

    });
});

});

输出:

[Error: eval failed: invoke failed: JS Error: TypeError: myFunction is not a function nofile_a:0]

我发现问题与包裹函数定义的引号(“”)有关。

在 mongo-cli 上:

> db.system.js.find()
{ "_id" : "myFunction", "value" : "function myFunction() { return 123; }" }

但之后:

> db.system.js.save({_id : "myFunction", value : function myFunction() { return 123; }});

> db.system.js.find()
{ "_id" : "myFunction", "value" : function cf__5__f_myFunction() {  
return 123;  
} }

db.eval("myFunction()"),有效!

所以,我的问题是:如何使用 node-mongodb-native 驱动程序从 node.js 保存存储过程?

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    在阅读了关于驱动数据类型的documentation 之后,我意识到我需要传递一个 mongo.Code 对象,而不是使用代码传递字符串:

    {
      "_id" : "myFunction",
      "value" : new mongo.Code("function myFunction() { return 123; }")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-10
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 2017-12-13
      相关资源
      最近更新 更多