Search code examples
javascriptreactjsgraphqlgraphql-jsexpress-graphql

Limiting or filtering a graphql query using apollo-express


I am new to graphql. I am building a react site with graphql on the backend. I am trying to figure out how to limit the number of objects (or items) returned by the resolver. Documentation is very scarce and i did not see clear examples for filtering or limiting or sorting things.

my index file looks like this:

import express from "express";
import mongoose from "mongoose";
import {ApolloServer, gql} from "apollo-server-express";
import {resolvers} from "./resolver"
import {typeDefs} from "./typeDefs"
const bodyParser = require('body-parser');

const server = async () => {

    const app = express();

    app.use(bodyParser.json());

    app.use((req, res, next) => {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'POST,GET,OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
        if (req.method === 'OPTIONS') {
          return res.sendStatus(200);
        }
        next();
      });


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

    server.applyMiddleware({app})

    await mongoose.connect("mongoaddr...",{useNewUrlParser:true})

    app.get('/', (req,res)=> res.send('hello'))
    app.listen({port:4001}, ()=>{
        console.log('connected')
    })

}

server()

My model:

import mongoose from "mongoose";
export const Post = mongoose.model("Post",{
    word:String, 

    )

my typeDefs:

import {gql} from "apollo-server-express";
export const typeDefs = gql`

type Query{

    getPosts(limit:Int):[Post!]!

}
type Post {
    id:ID!
    word: String!

}

And my resolver:

import { Post } from "./models/Post";


export const resolvers = {
    Query:{

        async getPosts(_,{ limit },context){
            const post = Post.find()
            console.log(limit)
            return(post)

        }}

}
Mutation:{...}

I do not understand at all how to limit the getPosts query. With Posts.find() i get all the items in my website but when i console.log it it gives me a huge chunk of metadata.

Could anybody please give an example of how to filter for lets say first 10 objects based on my situation. The data that i am filtering is in mongo db. so basically a standard json like :

{
  "data": {
    "getPosts": [
      {
        "word": "test"
      },
      {
        "word": "test1"
      }
    ]
  }
}

Solution

  • It's not related to grapql at all! You have to slice the array of documents you are getting from your your mongoose model. In your case the getPosts function will return an array of Post documents. So, you just have to slice & return the array.

    async getPosts(_,{ limit },context){
      const post = Post.find()
      return post.slice(0, limit)
    }}
    

    Or even better, you could use mongoose limits:

    async getPosts(_,{ limit },context){
      const post = Post.find().limit(limit)
      return post
    }}
    

    That's it 😉.