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

如何基于Mongoose Model自动生成REST API的Swagger文档?

无需手动注解,基于Mongoose Model自动生成Swagger文档

针对你遇到的mongoose-to-swagger输出格式不完整、swagger-jsdoc需要手动注解的问题,以下两种方案可以实现仅靠Mongoose Model自动生成符合swagger-ui-express要求的完整Swagger文档:


方案1:手动整合mongoose-to-swagger构建完整Swagger Spec

mongoose-to-swagger仅生成单个Model的Schema定义,我们可以手动将其嵌入完整的Swagger结构,并自动生成CRUD路由的Paths配置。

步骤1:安装依赖

npm install mongoose-to-swagger swagger-ui-express

步骤2:编写Swagger生成工具

创建swaggerGenerator.js文件,负责生成完整的Swagger规范:

const m2s = require('mongoose-to-swagger');
const Time = require('./models/Time'); // 导入你的Mongoose Model

// 生成Model对应的Swagger Schema
const schemas = {
  Time: m2s(Time)
};

// 自动生成CRUD风格的Paths配置
const generateCRUDPaths = (modelName, basePath = '/api/v1') => {
  const pathPrefix = `${basePath}/${modelName}`;
  return {
    [pathPrefix]: {
      get: {
        summary: `获取所有${modelName}数据`,
        responses: {
          200: {
            description: '成功返回数据列表',
            content: {
              'application/json': {
                schema: {
                  type: 'array',
                  items: { $ref: `#/components/schemas/${modelName}` }
                }
              }
            }
          }
        }
      },
      post: {
        summary: `创建新的${modelName}数据`,
        requestBody: {
          required: true,
          content: {
            'application/json': {
              schema: { $ref: `#/components/schemas/${modelName}` }
            }
          }
        },
        responses: {
          201: {
            description: '数据创建成功',
            content: {
              'application/json': {
                schema: { $ref: `#/components/schemas/${modelName}` }
              }
            }
          }
        }
      }
    },
    `${pathPrefix}/{id}`: {
      get: {
        summary: `根据ID获取单个${modelName}数据`,
        parameters: [
          {
            name: 'id',
            in: 'path',
            required: true,
            schema: { type: 'string' },
            description: `${modelName}的ID`
          }
        ],
        responses: {
          200: {
            description: '成功返回单个数据',
            content: {
              'application/json': {
                schema: { $ref: `#/components/schemas/${modelName}` }
              }
            }
          },
          404: { description: '数据不存在' }
        }
      },
      put: {
        summary: `根据ID更新${modelName}数据`,
        parameters: [
          {
            name: 'id',
            in: 'path',
            required: true,
            schema: { type: 'string' },
            description: `${modelName}的ID`
          }
        ],
        requestBody: {
          required: true,
          content: {
            'application/json': {
              schema: { $ref: `#/components/schemas/${modelName}` }
            }
          }
        },
        responses: {
          200: {
            description: '数据更新成功',
            content: {
              'application/json': {
                schema: { $ref: `#/components/schemas/${modelName}` }
              }
            }
          },
          404: { description: '数据不存在' }
        }
      },
      delete: {
        summary: `根据ID删除${modelName}数据`,
        parameters: [
          {
            name: 'id',
            in: 'path',
            required: true,
            schema: { type: 'string' },
            description: `${modelName}的ID`
          }
        ],
        responses: {
          200: { description: '数据删除成功' },
          404: { description: '数据不存在' }
        }
      }
    }
  };
};

// 构建完整的Swagger Spec
const swaggerSpec = {
  openapi: '3.0.0',
  info: {
    title: '基于Mongoose Model自动生成的API文档',
    version: '1.0.0',
    description: '无需手动注解,直接从Mongoose Model生成Swagger文档'
  },
  paths: generateCRUDPaths('Time'),
  components: { schemas }
};

module.exports = swaggerSpec;

步骤3:在Express中集成Swagger UI

在主入口文件(如app.js)中挂载Swagger文档:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./swaggerGenerator');

const app = express();

// 挂载Swagger UI页面
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

// 注册你的API路由
app.use('/api/v1/Time', require('./routes/timeRoutes'));

app.listen(3000, () => {
  console.log('Server running on port 3000');
  console.log('Swagger docs available at http://localhost:3000/api-docs');
});

方案2:使用express-mongoose-swagger自动生成

该库可直接扫描Express路由和Mongoose Model,自动生成完整的Swagger文档,无需手动注解。

步骤1:安装依赖

npm install express-mongoose-swagger

步骤2:在Express中配置

const express = require('express');
const expressMongooseSwagger = require('express-mongoose-swagger');
const Time = require('./models/Time');

const app = express();
app.use(express.json());

// 配置Swagger生成器
expressMongooseSwagger(app, {
  definition: {
    openapi: '3.0.0',
    info: {
      title: '自动生成的API文档',
      version: '1.0.0',
      description: '基于Express和Mongoose自动生成'
    }
  },
  basedir: __dirname, // 项目根目录
  files: ['./routes/**/*.js'] // 扫描所有路由文件
});

// 注册API路由(库会自动识别路由中使用的Mongoose Model)
app.use('/api/v1/Time', require('./routes/timeRoutes'));

app.listen(3000, () => {
  console.log('Server running on port 3000');
  console.log('Swagger docs available at http://localhost:3000/api-docs');
});

注意事项

  • mongoose-to-swagger会自动转换Mongoose类型到Swagger规范(如Date转为string+date-time格式),但自定义验证器(如endingTime的时间校验)需要手动在Swagger Schema中添加扩展字段补充说明。
  • 多Model场景下,方案1只需在schemas对象中添加更多m2s(Model)结果;方案2确保路由中使用对应Model即可自动识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 15:47:27