当前位置: 首页 > article >正文

MongoDB#Code和Function

背景

在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变更)


http://www.kler.cn/a/564573.html

相关文章:

  • Axure PR 9 中继器 03 翻页控制
  • 计算机网络之传输层(传输层的功能)
  • Ray Data 内部架构深度解析
  • C++ algorithm之shuffle函数
  • 光速解决phpstudy无法启动MySQL服务
  • Java—初始多线程
  • 【Java项目】基于Spring Boot的网上商城购物系统
  • 网络安全学习-常见安全漏洞检测以及修复方法-1
  • 泛微Ecode新增Button调用服务器中的JSP页面里的方法
  • Cannot resolve net.sf.json-lib:json-lib:2.4
  • 小红和小紫的拿球游戏(B组)
  • linux在vim中查找和替换
  • AI数据分析:用DeepSeek做数据清洗
  • ArcGIS Pro中打造精美高程渲染图的全面指南
  • 2025学年安徽省职业院校技能大赛 “信息安全管理与评估”赛项 比赛样题任务书
  • 数字IC后端设计实现OCC(On-chip Clock Controller)电路介绍及时钟树综合案例
  • 论文阅读笔记:Continual Forgetting for Pre-trained Vision Models
  • winfrom的progressBar 鼠标移上去显示 进度条的时间
  • 算法day2 dfs搜索2题
  • vscode下载安装教程(附安装包)vscode图文安装教程最新版