If I want to connect a mongo database to graphql schema, do I need mongoose ORM or can I just do raw drivers calls?
With the Mongoose adapter for Graffiti, you can use your existing Mongoose schema for developing a GraphQL. It's a query language used for APIs, created from any existing code by defining types and fields.
It's not mandatory to use Mongoose over the MongoDB Native API. However, there are some benefits to doing so.
No. GraphQL is often confused with being a database technology. This is a misconception, GraphQL is a query language for APIs - not databases. In that sense it's database agnostic and can be used with any kind of database or even no database at all.
You can do both.
If you have mongoose models already defined, you can use them while writing resolve
functions. See the following example.
var QueryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
todos: {
type: new GraphQLList(TodoType),
resolve: () => {
return new Promise((resolve, reject) => {
TODO.find((err, todos) => {
if (err) reject(err)
else resolve(todos)
})
})
}
}
})
})
If you don't have mongoose models or if you want to use mongodb native driver, you can do that too. Following is a simple example of doing so using MongoDB Node.JS Driver.
resolve: () => {
return new Promise((resolve, reject) => {
db.collection('todos').find({}).toArray((err, todos) => {
if (err) reject(err)
else resolve(todos)
})
})
}
If you have mongoose models and you want to generate GraphQL schema from them, you may be interested in graffiti-mongoose, which generates GraphQL types and schemas from existing mongoose models.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With