如何从Node.js将存储的JavaScript保存到mongodb中 [英] How can I save a stored javascript into mongodb from node.js
本文介绍了如何从Node.js将存储的JavaScript保存到mongodb中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码:
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]
我发现问题与包装函数定义的引号(")有关.
I found out that the problem is related to the quotes ("") wrapping the function definition.
在mongo-cli上:
On 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()")有效!
the db.eval("myFunction()"), works!
所以,我的问题是:如何使用node-mongodb-native驱动程序从node.js保存存储过程?
So, my question is: How can I save a stored procedure from node.js using the node-mongodb-native driver?
推荐答案
After reading the documentation about the driver data types, I realized that instead of passing the string with the code, I needed to pass a mongo.Code object:
{
"_id" : "myFunction",
"value" : new mongo.Code("function myFunction() { return 123; }")
}
这篇关于如何从Node.js将存储的JavaScript保存到mongodb中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文