Both Graphql and Mongoose are aim for improving and simplifing the developing workflow, but it is verbose to use them together, you have to build repeated Graphql type based on Mongoose schema, create simple CRUD method for each model. MooseQL is created to glue Mongoose to Graphql for making everything to become easy again.
Installation
npm install mongoose --save
Getting Started
1. Creating Mongoose model as usual
const userSchema = name: first: type: String required: 'first name required' last: String school: type: SchemaTypesObjectId ref: 'School' const UserModel = mongoose
2. Passing model to MooseQL to get GraphQL schema
const mySchema =
3. That's it, you can use it now, let's using express + express-graphql for example
Server side
const app = appapp
Client side
- Create a
Query
See we have a Mongoose schema for User model:
{
name: {
first: String,
last: {
fst: String,
snd: Number
}
},
userName: { type: String, required: [true, 'userName is required'] },
age: Number,
isBot: Boolean,
birth: { type: Date, default: Date.now },
binary: Buffer,
info: Schema.Types.Mixed,
hobbies: { type: [String], required: 'hobbies should have one at least' },
currentSchool: { type: Schema.Types.ObjectId, ref: 'School' },
education: [{ type: Schema.Types.ObjectId, ref: 'School' }]
}
You can query like this after using mooseql to generate the schema
`{ user ( id: "" name_first: "wayne", userNames: ["wwayne01", "wwayne02"], age: 1, isBot: false, birth: "", binary: "", hobbies: ["basketball"], currentSchool: "" education: [""] ) { id name { first } currentSchool { id name } education { id } } }`
Key points:
- Query by id or ids is available for every model
- You can query by plural of the attribute, e.g.
name -> names
- If the attribute is plural, you can't query by its singular
- When you want to use an object as query arguments, use
_
to replace.
, e.g.:name.first
->name_first
- Attribute of Mixed type is not supported to be query arguments
- The response is always an Array
Mutation
Create
The mutation of create is create{modelName}
, if the attribute of the model is defined as required in Mongoose shema, it is required as well for create mutaion. Using User model for example:
`mutation createMyUser { user: createUser( userName: "wwayne", hobbies: ["This", "is", "Required"], currentSchool: "" ) { id userName currentSchool { id } }}`
Update
The mutation of update is update{modelName}
. Currently update only support single document update, which means the argument id
is required and plural attribute can't be used as argument unless it is plural originally. For example, userNames
is not supposed to be an argument, but hobbies
and education
could.
Using User model for example:
`mutation updateMyUser { user: updateUser( id: "" userName: "wwayne" ) { id userName }}`
Delete
The mutation of delete is delete{modelName}
. Currently delete only support single document update, so it only accept id
as argument.
The response is { success: {Bool}, msg: {String or null} }
Using User model for example:
`mutation deleteMyUser { result: deleteUser( id: "" ) { success msg }}`
Supported type
All Mongoose types are supported
- String
- Number
- Date
- Buffer
- Boolean
- Mixed (Can't be used as argument in query and mutation)
- ObjectId (Must be accompanied with
ref
) - Array
In addition, the object type is supported as well, but you have to use _
to replace .
when using it as argument, because Graphql only support /.[a-z][A-Z][0-9]/ as name convention for the moment.
Mongoose: name { first: { one: String, two: Number }, last: String }
user (
name_first_one: "firstOne",
name_first_two: 21,
name_last: "nameLast"
) {
id
}
Extend schema
Mooseql will generate some basic CRUD methods which may not enough for you, then you need to define your own schema.
buildTypes
To make it easy, Mooseql exposes an method called buildTypes
which used for converted Mongoose model to Graphql Type
import mooseql, { buildTypes } from 'mooseql'
Extend default schema
See you have two models UserModel
and SchoolModel
, you can extend schema like following:
// typeMap = {User: GraphqlUserType, School: GraphqlSchoolType }const typeMap = const mySchema =
So it just pass { query: {Your custom queries}, mutation: {Your custom mutations} }
into mooseql()
as the second argument.
Advanced usage
Make use of context
In practice, we store the session in req.session or logged in user data in req.user, and it is usually passed to graphql as context. In this situation, you just need to add an option context
in your Mongoose schema. Let's using express + express-graphql + password + express-session for example.
See you have a model named Article, the author is logged in user, so Mongoose schema may like the following:
const articleSchema = title: String author: type: SchemaTypesObjectId required: true ref: 'User' context: 'user.id'
Since express-graphql will use request
object as context if nothing set to context, and passport will set user object into req.user
, express-session will use req.session
. So your context is probably like
user: userObject session: sessionObject
That's why you set context: 'user.id'
in your Mongoose schema, because the path author
only store an ObjectId, so it only cares about user.id
instead of the completed user object.
In this way, after user login, when you create an new article, you don't need to pass the autor as params even though it has been set to required
, the author will be got from req.user.id
automatically. The query string is like:
`mutation create { article: createArticle ( title: "How to use graphql" ) { id title author { id userName } }}`
License
MIT