Graphql-tools: How do I use the mongoose in the resolvers?

Created on 28 Jan 2018  ·  4Comments  ·  Source: ardatan/graphql-tools

I want use mongoose in graphql-tools。

I use Typescript.

my models code:

import * as mongoose from 'mongoose';
interface IBook extends mongoose.Document {
  title: string;
}
const bookSchema = new mongoose.Schema({
  title: String,
});
//mongoose.model(modelName, schema);
export const Book = mongoose.model<IBook>('Book', bookSchema);

my graphql-tools schema code:

import { makeExecutableSchema } from 'graphql-tools';
import { resolvers } from '../resolvers/resolver';

const typeDefs = `
  type Query { 
    books: [Book] 
  }
  type Book { 
    title: String
  }
`;
export const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

my graphql-tools resolvers code:

import {Book} from '../models/book';

// The resolvers
export const resolvers = {
  Query: {
    books(title: any) {
      Book.find({ title }, (err, data) => {
        return data;
      });
    }  
  }
};

my index.ts code:

import { graphiqlKoa, graphqlKoa } from 'apollo-server-koa';
import { schema } from './schemas/scheme';
import { Book } from './models/book';

router.post('/graphql', graphqlKoa({
  schema
  })
);
outer.get('/graphiql',
  graphiqlKoa({
    endpointURL: '/graphql'
  }
));

then i query books return null.

Uploading <a href="WX20180128-231941@2x.png">WX20180128-231941@2x.png</a>…

my mongodb :

I don’t know where I am having problems。

Most helpful comment

Thanks everyone,I sloved my problem.I forget async....

All 4 comments

Your resolver for book makes a call to the Books model and inside the arrow function callback you are returning the data, it is not being captured as the return of the resolver hence the resolver itself implies a return null.

Explicitly performing like so.

  import {Book} from '../models/book';

  // The resolvers
  export const resolvers = {
    Query: {
      books(title: any) {
        Book.find({ title }, (err, data) => {
          return data;
        });
        return null;
      }  
    }
  };

@karloluis Don't you need to return Book.find(...) from the resolver function?

@benjamn That is a possibility, the code I wrote is how the code he wrote is being interpreted by Javascript. As you pointed out, the callback would need it's own return with the expected value. It is not a graph-tools issue.

Thanks everyone,I sloved my problem.I forget async....

Was this page helpful?
0 / 5 - 0 ratings

Related issues

avnersorek picture avnersorek  ·  3Comments

radiegtya picture radiegtya  ·  5Comments

capaj picture capaj  ·  4Comments

benjaminhon picture benjaminhon  ·  3Comments

udisun picture udisun  ·  3Comments