You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合MongoDB $jsonSchema与json-schema-to-typescript生成TS接口?

可行方案:兼容MongoDB $jsonSchema与TypeScript类型生成

方案1:编写双标准兼容的Schema

直接维护一份同时包含bsonType(供MongoDB验证)和标准JSON Schema type(供TS类型生成)的Schema,两边各自读取对应字段,无需额外转换。

示例Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "bsonType": "object",
  "type": "object",
  "required": ["name", "age"],
  "properties": {
    "name": {
      "bsonType": "string",
      "type": "string",
      "minLength": 2
    },
    "age": {
      "bsonType": "int",
      "type": "integer",
      "minimum": 18
    },
    "email": {
      "bsonType": "string",
      "type": "string",
      "format": "email"
    }
  }
}

MongoDB创建集合时会读取bsonType做验证,json-schema-to-typescript则基于type生成TS接口,完全适配双方需求。

方案2:MongoDB Schema转标准JSON Schema脚本

如果不想写重复字段,可以单独维护MongoDB风格的Schema,再用简单脚本将bsonType映射为标准JSON Schema的type,再喂给类型生成工具。

核心映射规则

  • bsonType: "string" → type: "string"
  • bsonType: "int"/"long" → type: "integer"
  • bsonType: "double"/"decimal" → type: "number"
  • bsonType: "object" → type: "object"
  • bsonType: "array" → type: "array"
  • bsonType: "bool" → type: "boolean"
  • bsonType: "date" → type: "string"(或Date,按需选择)

示例转换脚本:

const fs = require('fs');
const { compileFromFile } = require('json-schema-to-typescript');

// 读取MongoDB Schema
const mongoSchema = require('./mongo-schema.json');

// 递归转换bsonType为type
function convertBsonToJsonSchema(schema) {
  const converted = { ...schema };
  if (converted.bsonType) {
    converted.type = mapBsonType(converted.bsonType);
  }
  // 处理嵌套属性
  if (converted.properties) {
    Object.keys(converted.properties).forEach(key => {
      converted.properties[key] = convertBsonToJsonSchema(converted.properties[key]);
    });
  }
  // 处理数组项
  if (converted.items) {
    converted.items = convertBsonToJsonSchema(converted.items);
  }
  return converted;
}

function mapBsonType(bsonType) {
  switch(bsonType) {
    case 'string': return 'string';
    case 'int': case 'long': return 'integer';
    case 'double': case 'decimal': return 'number';
    case 'object': return 'object';
    case 'array': return 'array';
    case 'bool': return 'boolean';
    case 'date': return 'Date';
    default: return 'any';
  }
}

// 生成TS类型
const jsonSchema = convertBsonToJsonSchema(mongoSchema);
fs.writeFileSync('./temp-schema.json', JSON.stringify(jsonSchema, null, 2));

compileFromFile('./temp-schema.json')
  .then(ts => fs.writeFileSync('./types.ts', ts))
  .catch(err => console.error(err));

可以把这个脚本加入npm scripts,每次Schema变更后自动执行生成类型。

方案3:自定义json-schema-to-typescript解析器

直接扩展json-schema-to-typescript的类型解析逻辑,让它支持识别bsonType字段,无需修改原始Schema。

示例配置:

const fs = require('fs');
const { compile, Config } = require('json-schema-to-typescript');
const mongoSchema = require('./mongo-schema.json');

// 自定义解析器,优先处理bsonType
const config = new Config();
config.typeParser = (schema, ctx) => {
  if (schema.bsonType) {
    switch(schema.bsonType) {
      case 'string': return 'string';
      case 'int': case 'long': case 'double': return 'number';
      case 'object': return 'object';
      case 'array': return `Array<${config.typeParser(schema.items, ctx)}>`;
      case 'bool': return 'boolean';
      case 'date': return 'Date';
      case 'objectId': return 'string'; // 或导入mongodb的ObjectId类型
      default: return 'any';
    }
  }
  //  fallback到默认解析逻辑
  return config.defaultTypeParser(schema, ctx);
};

// 生成TS接口
compile(mongoSchema, 'User', config)
  .then(ts => fs.writeFileSync('./types.ts', ts))
  .catch(err => console.error(err));

额外提示

  • 对于MongoDB特有的类型(如objectId),可以映射为TS的string或直接使用mongodb包中的ObjectId类型。
  • 把类型生成逻辑集成到项目构建流程中,实现Schema变更后的自动类型更新,减少手动操作。

内容的提问来源于stack exchange,提问作者mr_robot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 17:43:29