{"id":14975702,"url":"https://github.com/danishsiraj/mongoose-graphql-server","last_synced_at":"2025-10-26T02:13:22.306Z","repository":{"id":60583858,"uuid":"543989260","full_name":"DanishSiraj/mongoose-graphql-server","owner":"DanishSiraj","description":null,"archived":false,"fork":false,"pushed_at":"2023-10-07T16:51:13.000Z","size":331,"stargazers_count":7,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-01T06:23:24.591Z","etag":null,"topics":["graphql","hacktoberfest","mongoose"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DanishSiraj.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-10-01T10:44:32.000Z","updated_at":"2024-03-16T18:05:33.000Z","dependencies_parsed_at":"2022-10-01T18:10:20.233Z","dependency_job_id":null,"html_url":"https://github.com/DanishSiraj/mongoose-graphql-server","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanishSiraj%2Fmongoose-graphql-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanishSiraj%2Fmongoose-graphql-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanishSiraj%2Fmongoose-graphql-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanishSiraj%2Fmongoose-graphql-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DanishSiraj","download_url":"https://codeload.github.com/DanishSiraj/mongoose-graphql-server/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238508784,"owners_count":19484204,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphql","hacktoberfest","mongoose"],"created_at":"2024-09-24T13:52:24.882Z","updated_at":"2025-10-26T02:13:17.263Z","avatar_url":"https://github.com/DanishSiraj.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"Automatically generates a GraphQL Server from mongoose models. Provides all the basic CRUD operations for all models on both native mongoose connection as well as created connections. Supports deep nested populations for queries.\n\nUses [graphql-compose-mongooose](https://github.com/graphql-compose/graphql-compose-mongoose) and [Apollo Server](https://www.apollographql.com/docs/apollo-server/) under the hood.\n\n- [Installation](#installation)\n- [Example](#example)\n  - [Running with Mongoose](#running-with-mongoose)\n  - [Nested Populations](#nested-populations)\n    - [With Model Names](#with-model-names)\n    - [With Virtuals](#with-virtuals)\n  - [Using Express Server](#using-express-server)\n    - [As Express Middleware](#as-express-middleware)\n    - [From GraphQL Server](#from-graphql-server)\n    - [Using Existing Instance](#using-existing-instance)\n- [Adding Custom Query and Mutations](#adding-custom-query-and-mutations)\n- [Configuration](#configuration)\n  - [Configuring Apollo Server](#configuring-apollo-server)\n- [Known Issues](#issues)\n- [ToDo List](#todo)\n\n## Installation\n\nInstall with npm\n\n```console\n$ npm i mongoose-graphql-server --save\n```\n\nInstall with yarn\n\n```console\n$ yarn add mongoose-graphql-server\n```\n\n## Example\n\nUse the endpoint `/graphql` to open graphQL studio. The examples to implement can also be found here at [examples repository](https://github.com/DanishSiraj/mongoose-graphql-examples)\n\n#### Running with Mongoose\n\n```\nconst mongoose = require('mongoose');\nconst {\n  generateSchema,\n  createGraphQLServer,\n} = require('mongoose-graphql-server');\nconst PORT = process.env.port || 3000;\n\nmongoose.connect('mongodb://localhost/test');\nconst db = mongoose.connection;\n\nconst init = async () =\u003e {\n\n// Register models\n\nconst Cat = mongoose.model('Cat', { name: String });\n\n// Build the schema\n\nconst schema = generateSchema(mongoose);\n\n// Create the graphQL server\n\nconst app = await createGraphQLServer(schema);\n\n// Start the server\n\napp.listen(PORT, () =\u003e {\n  console.log(`Server is running at http://localhost:${PORT}/`);\n  console.log(`GraphQL is running at http://localhost:${PORT}/graphql`);\n})\n\n}\n\ndb.once('open',init);\n```\n\n### Nested Populations\n\nThis package supports deep nested populations if using model names as refs or defining virtual fields on the models.\n\n#### With Model Names\n\nDefine the first `User` model in `user.model.js` file\n\n```\nconst {model, Schema, Types} = require('mongoose');\n\n\nconst userSchema = new Schema(\n  {\n    name: {\n      type: String,\n    },\n    username: {\n    type: String,\n    required: true,\n    indexed: true\n    },\n    isActive: {\n      type: Boolean,\n      default: true,\n    }\n    ,\n    posts:[{\n    type: Types.ObjectId,\n    ref: \"post\",\n    }]\n\n  },\n  {\n    timestamps: true,\n    toObject: {\n      virtuals: true,\n    },\n    toJSON: {\n      virtuals: true,\n    },\n  }\n);\n\nconst userModel = model('user', userSchema);\nmodule.exports = userModel;\n```\n\nDefine the second `Post` model in `post.model.js` file\n\n```\nconst {model, Schema,Types} = require('mongoose');\n\nconst postSchema = new Schema(\n  {\n    title: {\n      type: String,\n      required: true,\n    },\n\n    description: {\n      type: String,\n    },\n\n    status: {\n      type: String,\n      enum: ['CREATED', 'DRAFT', 'PUBLISHED'],\n      required: true,\n    },\n    creator: {\n      type: Types.ObjectId,\n      ref:\"user\"\n    },\n  },\n  {\n    timestamps: true,\n    toObject: {\n      virtuals: true,\n    },\n    toJSON: {\n      virtuals: true,\n    },\n  }\n);\n\n\nconst postModel = model('post', postSchema);\nmodule.exports = postModel;\n```\n\nCreate the server file `index.js`\n\n```\nconst mongoose = require('mongoose');\nconst {\n  generateSchema,\n  createGraphQLServer,\n} = require('mongoose-graphql-server');\nconst PORT = process.env.port || 3000;\n\nmongoose.connect('mongodb://localhost/test1');\nconst db = mongoose.connection;\n\nconst init = async () =\u003e {\n\n// Register models\nrequire('./user.model.js');\nrequire('./post.model.js');\n\n// Build the schema\nconst schema = generateSchema(mongoose);\n\n// Create the graphQL server\nconst app = await createGraphQLServer(schema);\n\n// Start the server\napp.listen(PORT, () =\u003e {\n  console.log(`Server is running at http://localhost:${PORT}/`);\n  console.log(`GraphQL is running at http://localhost:${PORT}/graphql`);\n})\n\n}\n\ndb.once('open',init);\n```\n\nRun the server\n\n```console\n$ node index.js\n```\n\n#### With Virtuals\n\nDefine the first `User` model in `user.model.js` file\n\n```\nconst {model, Schema} = require('mongoose');\n\nconst userSchema = new Schema(\n  {\n    name: {\n      type: String,\n    },\n    isActive: {\n      type: Boolean,\n      default: true,\n    },\n  },\n  {\n    timestamps: true,\n    toObject: {\n      virtuals: true,\n    },\n    toJSON: {\n      virtuals: true,\n    },\n  }\n);\n\nuserSchema.virtual('posts', {\n  ref: 'post',\n  foreignField: 'author_id',\n  localField: '_id',\n});\n\n\nconst userModel = model('user', userSchema);\nmodule.exports = userModel;\n\n```\n\nDefine the second `Post` model in `post.model.js` file\n\n```\nconst {model, Schema} = require('mongoose');\n\nconst postSchema = new Schema(\n  {\n    title: {\n      type: String,\n      required: true,\n    },\n\n    description: {\n      type: String,\n    },\n\n    status: {\n      type: String,\n      enum: ['CREATED', 'DRAFT', 'PUBLISHED'],\n      required: true,\n    },\n    author_id: {\n      type: String,\n      required: true,\n    },\n  },\n  {\n    timestamps: true,\n    toObject: {\n      virtuals: true,\n    },\n    toJSON: {\n      virtuals: true,\n    },\n  }\n);\n\npostSchema.virtual('author', {\n  ref: 'user',\n  foreignField: '_id',\n  localField: 'author_id',\n  justOne: true,\n});\n\nconst postModel = model('post', postSchema);\nmodule.exports = postModel;\n\n```\n\nCreate the server file `index.js`\n\n```\nconst mongoose = require('mongoose');\nconst {\n  generateSchema,\n  createGraphQLServer,\n} = require('mongoose-graphql-server');\nconst PORT = process.env.port || 3000;\n\nmongoose.connect('mongodb://localhost/test');\nconst db = mongoose.connection;\n\nconst init = async () =\u003e {\n\n// Register models\nrequire('./user.model.js');\nrequire('./post.model.js');\n\n// Build the schema\nconst schema = generateSchema(mongoose);\n\n// Create the graphQL server\nconst app = await createGraphQLServer(schema);\n\n// Start the server\napp.listen(PORT, () =\u003e {\n  console.log(`Server is running at http://localhost:${PORT}/`);\n  console.log(`GraphQL is running at http://localhost:${PORT}/graphql`);\n})\n\n}\n\ndb.once('open',init);\n\n```\n\nRun the server\n\n```console\n$ node index.js\n```\n\n### Using Express Server\n\nThis package uses express as the default server to serve the graphQl endpoint, the `createGraphQLServer` method returns an Express app instance. Further the server can be used as an express app middleware by using `createGraphQLMiddleware`.\n\n#### As Express Middleware\n\n```\nconst mongoose = require('mongoose');\nconst express = require('express');\n\nconst {\n  generateSchema,\n  createGraphQLMiddleware\n} = require('mongoose-graphql-server');\nconst PORT = process.env.port || 3000;\n\n\nmongoose.connect('mongodb://localhost/test');\nconst db = mongoose.connection;\n\nconst init = async () =\u003e {\n\n  // Register models\n  const Cat = mongoose.model('Cat', { name: String });\n  // Build the schema\n  const schema = generateSchema(mongoose);\n\n  let app = express();\n\n  const middleware = await createGraphQLMiddleware(schema);\n\n  app.use(\"/\", middleware);\n\n\n  // Start the server\n  app.listen(PORT, () =\u003e {\n    console.log(`Server is running at http://localhost:${PORT}/`);\n    console.log(`GraphQL is running at http://localhost:${PORT}/graphql`);\n  })\n\n}\n\ndb.once('open', init);\n```\n\n#### From GraphQL Server\n\n```\nconst mongoose = require('mongoose');\nconst {\n  generateSchema,\n  createGraphQLServer,\n} = require('mongoose-graphql-server');\nconst PORT = process.env.port || 3000;\n\nmongoose.connect('mongodb://localhost/test');\nconst db = mongoose.connection;\n\nconst init = async () =\u003e {\n\n// Register models\nconst Cat = mongoose.model('Cat', { name: String });\n// Build the schema\nconst schema = generateSchema(mongoose);\n\n// Create the graphQL server\nconst app = await createGraphQLServer(schema);\n\napp.get(\"/\",(req,res) =\u003e {\nres.send(\"hello\");\n})\n\n// Start the server\napp.listen(PORT, () =\u003e {\n  console.log(`Server is running at http://localhost:${PORT}/`);\n  console.log(`GraphQL is running at http://localhost:${PORT}/graphql`);\n})\n\n}\n\ndb.once('open',init);\n```\n\nRun the server\n\n```console\n$ node index.js\n```\n\n#### Using Existing Instance\n\n```\nconst mongoose = require('mongoose');\nconst express = require('express');\n\nconst {\n  generateSchema,\n  createGraphQLServer,\n} = require('mongoose-graphql-server');\nconst PORT = process.env.port || 3000;\n\nmongoose.connect('mongodb://localhost/test');\nconst db = mongoose.connection;\n\nconst init = async () =\u003e {\n\n  // Register models \n  const Cat = mongoose.model('Cat', { name: String });\n  // Build the schema\n  const schema = generateSchema(mongoose);\n\n  let app = express();\n  app.get(\"/\", (req, res) =\u003e {\n    res.send(`GrahpQL running on http://localhost:${PORT}/graphql`);\n  })\n\n  // Create the graphQL server\n  app = await createGraphQLServer(schema, app);\n\n  app.get(\"/test\", (req, res) =\u003e {\n    res.send(\"ok\")\n  })\n\n  // Start the server\n  app.listen(PORT, () =\u003e {\n    console.log(`Server is running at http://localhost:${PORT}/`);\n    console.log(`GraphQL is running at http://localhost:${PORT}/graphql`);\n  })\n\n}\n\ndb.once('open', init);\n```\n\nRun the server\n\n```console\n$ node index.js\n```\n\n## Adding Custom Query and Mutations\n\nWhen needed custom Query and Mutation fields can be defined in the GraphQl schema by using ```addQueryFields``` and ```addMutationFields``` functions. Additional types can also be defined using the ```schemaComposer``` which is an instance of SchemaComposer from [graqhql-compose](graphql-compose.github.io). Full documentation for customization can be found on their official [docs](https://graphql-compose.github.io/docs/basics/understanding-types.html) page.\n\n```\nconst mongoose = require('mongoose');\nconst {\n    generateSchema,\n    createGraphQLServer,\n    addQueryFields,\n    addMutationFields,\n    schemaComposer\n} = require('mongoose-graphql-server');\nconst PORT = process.env.port || 3000;\n\nmongoose.connect('mongodb://localhost/test');\nconst db = mongoose.connection;\n\nconst init = async () =\u003e {\n\n    // Register models \n    const Cat = mongoose.model('Cat', { name: String });\n\n    // Build the schema\n    let schema = generateSchema(mongoose);\n\n    // Add custom types and input types\n    const Test = schemaComposer.createObjectTC(`\n    type Test {\n        name: String\n        age: Int\n    }\n    `);\n\n    const TestInput = schemaComposer.createInputTC(`\n    input TestInput {\n        name: String\n    }`);\n\n    // Add custom query fields\n    addQueryFields({\n        \"testQuery\": {\n            type: [Test],\n            args: { input: TestInput },\n            resolve: (source, args, context, info) =\u003e {\n                return [{ \"name\": \"test\", \"age\": 1 }];\n            },\n        }\n    })\n\n    // Add custom mutation fields\n    addMutationFields({\n        \"testMutation\": {\n            type: [Test],\n            args: { input: TestInput },\n            resolve: (source, args, context, info) =\u003e {\n                return [{ \"name\": \"test\", \"age\": 1 }];\n            },\n        }\n    })\n\n    //rebuild the schema\n    schema = schemaComposer.buildSchema();\n\n    // Create the graphQL server\n    const app = await createGraphQLServer(schema);\n\n    // Start the server\n\n    app.listen(PORT, () =\u003e {\n        console.log(`Server is running at http://localhost:${PORT}/`);\n        console.log(`GraphQL is running at http://localhost:${PORT}/graphql`);\n    })\n\n}\n\ndb.once('open', init);\n```\n\n## Configuration\n\n### Configuring Apollo Server\n\nFeatures like schema introspection, cache, csrfPrevention can be configured by passing in the Apollo Server Configuration Object in the `createGraphQLServer` method.\n\n```\nconst app = await createGraphQLServer({\n  schema,\n  introspection: false\n});\n```\n\nThe full list of customization options can be found at [Apollo Server Docs](https://www.apollographql.com/docs/apollo-server/api/apollo-server)\n\n## Issues\n\n- At the moment populations are supported only on virtual fields and model names.\n- Supports sort and filter only on indexed fields at the moment.\n- Populating key needs to be present for deep nested populations of virtual fields.\n\n## ToDo\n\n- [x] Write the documentation\n- [ ] Write Tests\n- [ ] Fix issues\n- [x] Support custom field generator on genrated schema\n- [x] Addition of custom query and mutation resolvers\n- [x] Converting this project to typescript\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanishsiraj%2Fmongoose-graphql-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdanishsiraj%2Fmongoose-graphql-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanishsiraj%2Fmongoose-graphql-server/lists"}