Search code examples
expressmongooseswagger

Reference mongoose schema definition in swagger-jsdoc?


I've built a express.js project with a mongoDB backend using mongoose. Since I've created the mongoose models via mongoose schemas, I was wondering if it is possible to reference to the mongoose schema definition instead of re-typing all it's contents.

I'm currently using swagger-jsdoc.

Thanks and best regards

[/EDIT] I understand, that mongoose-to-swagger basically performs this task. However, I have no clue how I can reference to such a generated swagger schema within my swagger-jsdoc code comments.


Solution

  • I had the exact same issue and how i resolved it was i made a file called swaggerSchemas where i exported all the schemas like in the following example:

    export default {
      user: m2s(User),
    };
    

    Where User is the mongoose model. And finally inside your swagger jsdoc options you need something like the following:

    const options = {
          definition: {
           ...
            components: {
              schemas: swaggerSchemas,
            },
           ...
          },
          ...
    };