Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need mongoose with graphql?

If I want to connect a mongo database to graphql schema, do I need mongoose ORM or can I just do raw drivers calls?

like image 387
omgj Avatar asked May 15 '16 11:05

omgj


People also ask

Can I use GraphQL With Mongoose?

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.

Is it mandatory to use Mongoose with Node application?

It's not mandatory to use Mongoose over the MongoDB Native API. However, there are some benefits to doing so.

Do you need a database with GraphQL?

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.


1 Answers

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.

like image 98
Ahmad Ferdous Avatar answered Oct 04 '22 05:10

Ahmad Ferdous