0

How to connect mongodb with graphql without mongoose ?

Dadep
  • 2,796
  • 5
  • 27
  • 40

2 Answers2

0

You can use the mongodb library and pass it as argument via context on 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();

Passing mongo via context you can access on your resolvers:

Query: {
    allLinks: async (root, data, { mongo: { Links } }) =>
      Links.find({}).toArray(),
}
Alessander França
  • 2,697
  • 2
  • 29
  • 52
  • Im beginner for this area, your help might be appreciated i got below error. (node:4532) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect. (node:4532) UnhandledPromiseRejectionWarning: TypeError: db.collection is not a function (node:4532) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. – Kaviyarasu Palanisamy Aug 30 '18 at 13:01
  • You can help me, starting adding your code on your question. – Alessander França Aug 30 '18 at 13:09
  • this is a mongo error, it was just google it: https://stackoverflow.com/questions/50448272/avoid-current-url-string-parser-is-deprecated-warning-by-setting-usenewurlpars – Alessander França Aug 31 '18 at 11:09
0

Throws error.

    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();