我需要使用graphql的猫鼬吗? [英] Do I need mongoose with graphql?

查看:22
本文介绍了我需要使用graphql的猫鼬吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想将 mongo 数据库连接到 graphql 模式,我需要 mongoose ORM 还是我可以只调用原始驱动程序?

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

推荐答案

两者都可以.

如果您已经定义了猫鼬模型,您可以在编写 resolve 函数时使用它们.请参阅以下示例.

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)
          })
        })
      }
    }
  })
})

如果您没有 mongoose 模型,或者您想使用 mongodb 本机驱动程序,您也可以这样做.以下是使用 MongoDB Node.JS Driver 执行此操作的简单示例.

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)
    })
  })
}

如果你有猫鼬模型并且想从中生成 GraphQL 模式,你可能对 graffiti- 感兴趣mongoose,它从现有的 mongoose 模型生成 GraphQL 类型和模式.

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.

这篇关于我需要使用graphql的猫鼬吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆