背景
在MongoDB Shell中, 使用db.system.js.inertOne
新增一个自定义函数后,读取值类型显示Code Class
,该如何使用?Code类型和Function能互相转换吗?
实践
// 保存一个函数到 system.js 集合
db.system.js.insertOne({_id: "myFunction",value: function(x) { return x * 2; }
});// 查询 -> Code('function(x) {return x * 2;}')
const myFunction = db.system.js.findOne({ _id: "myFunction" }).value;
// 直接调用执行myFunction报错:myFunction is not a function.// 转换成Function -> [Function (anonymous)]
const myFunc = eval(`(${myFunction.code})`)// 执行 -> 4
myFunc(2)
转换
// Function -> Code
const myFunc = function() {return 'hello world!';}
const myCode = new Code(myFunc.toString())// Code -> Function
const sumCode = new Code('function(a, b) { return a + b; }')
const sumFunc = new Fucntion('return ' + sumCode.code)
sumFunc()(1, 2)
注意
- 以上都是在
MongoDB Shell
中操作 - Code Class详见
- TypeError: xxx is not a function
说明xxx函数或类型在当前版本中已经被移除或不再支持(
注意版本API变更
)