Imre_G
Imre_G

Reputation: 2535

Implementing pagination with Mongoose and graphql-yoga

I am experimenting with graphql and have created a simple server using graphql-yoga. My Mongoose product model queries my database and both resolvers return data as expected. So far it all works and I am very happy with how easy that was. However, I have one problem. I am trying to add a way to paginate the results from graphQL.

What did I try?

1) Adding a limit parameter to the Query type.

2) Accessing the parameter through args in the resolver

Expected behaviour

I can use the args.limit parameter in my resolver and use it to alter the Mongoose function

Actual behaviour

I can't read the arg object.

Full code below. How do I reach this goal?

import { GraphQLServer } from 'graphql-yoga'
import mongoose from "mongoose"
import {products} from "./models/products.js"

const connection = mongoose.connect('mongodb://myDB')

const prepare = (o) => {
  o._id = o._id.toString()
  return o
}

const typeDefs = `
  type Product {
    _id: String
    name: String
    description: String
    main_image: String
    images: [String]
  }

  type Query {
    product(_id: String): Product
    products(limit: Int): [Product]
  }
`

const resolvers = {
  Query: {
    product: async (_id) => {
      return (await products.findOne(_id))
    },
    products: async (args) => {
      console.log(args.name)
      return (await products.find({}).limit(args.limit))
    },
  },
}

const server = new GraphQLServer({ 
  typeDefs, 
  resolvers 
})

server.start(() => console.log('Server is running on localhost:4000'))

Upvotes: 0

Views: 568

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84877

The arguments for a field are the second parameter passed to the resolver; the first parameter is the value the parent field resolved to (or the root value in the case of queries/mutations). So your resolvers should look more like this:

product: (root, { _id }) => {
  return products.findOne(_id)
}

Upvotes: 1

Related Questions