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.

my mongodb :

I don’t know where I am having problems。
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....
Most helpful comment
Thanks everyone,I sloved my problem.I forget async....