如何在没有猫鼬的情况下将mongodb与graphql连接

时间:2018-08-30 11:08:37

标签: mongodb graphql

如何在没有mongodb的情况下将graphqlmongoose连接起来?

2 个答案:

答案 0 :(得分:0)

您可以使用mongodb库并将其作为参数通过graphqlexpress上的上下文传递

import { MongoClient } from 'mongodb';
import { graphqlExpress } from 'graphql-server-express';
import express from 'express';

const MONGO_URL = 'mongodb://localhost:27017/your_db';
const app = express();

const startServer = async () => {
  const db = await MongoClient.connect(MONGO_URL);

  const mongo = {
    Links: db.collection('links'),
    Users: db.collection('users')
  };

  const buildOptions = {
    schema: your_schema,
    context: { mongo },
  }

  app.use('/graphql', bodyParser.json(), graphqlExpress(buildOptions));

};
startServer();

通过上下文传递mongo可以在解析器上访问

Query: {
    allLinks: async (root, data, { mongo: { Links } }) =>
      Links.find({}).toArray(),
}

答案 1 :(得分:0)

抛出错误。

    import { MongoClient } from 'mongodb';
import { graphqlExpress } from 'graphql-server-express';
import express from 'express';

const MONGO_URL = 'mongodb://localhost:27017/test';
const app = express();

const startServer = async () => {
  const db = await  MongoClient.connect(MONGO_URL);

  const mongo = {
    posts: db.collection('mern'),

  };

  var schema = buildSchema(`

  type nodemerndata{
    _id : string
    lable: string
    value: string
    class : string
  }
`);

 var root = { 
    allLinks: async (root, data, { mongo: { posts } }) =>
      posts.find({}).toArray(),

}; 

const buildOptions = {
    schema: schema,
    context: { mongo },
    root:root
}



  app.use('/graphql', bodyParser.json(), graphqlExpress(buildOptions));
  app.listen(5000, () => console.log('Now browse to localhost:5000/graphiql'));

 };
startServer();