0

I am learning GraphQL and I have two Object types.

Say, they look like this

Say, The book type looks like this

const BookType = new GraphQLObjectType({  
    name: 'Book',  
    fields: () => ({ 
        id: { type:  GraphQLID},
        name: { type: GraphQLString},
        genre: { type: GraphQLString }, 
        author: { 
            type: authorType,
            resolve(parents, args) {
               Author.findOne( 
                   {
                    name: parents.authorName
                   }, function(err, result) {
                       console.log(result)
                       return result
                   })
            }
        }

    })
})

and Author Type looks like this

const authorType = new GraphQLObjectType({  
    name: 'author',  
    fields: () => ({ 
        id: { type:  GraphQLID},
        name: { type: GraphQLString},
        age: { type: GraphQLInt },
        books: {  
            type: new GraphQLList(BookType), 
            resolve(parent, args) {
            }
        }
    })
})

Now, I am adding data through Mutation (Not sharing it because I think it is irrelevant) and then run query in graphql to add data in Book Type. It correctly displays data for name, genre, id but for authorType it is showing the data as null while the console].log results log something like this in console

//This is console log in terminal
{ age: 'none',
  _id: 5bcaf8904b31d50a2148b60d,
  name: 'George R Martin',
  __v: 0 }

THis is the query I am running in graphiql

mutation{
        addBooks( 
           name: "Game of Thrones",
           genre: "Science Friction", 
            authorName: "George R Martin"
            ) {
           name,
           genre,
           author {
           name
                }
              }
           }

My entire schema is available here

Can someone please-please help me figure out what could I be doing wrong?

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210

1 Answers1

2

A resolver must return either some value or a Promise that will resolve in a value -- if it doesn't the field being resolved will return null. So there's two things off about your code. One, you don't return either a value or a Promise. Two, you return something inside a callback, but that's not actually doing anything, since most libraries disregard the return value of a callback function anyway.

You can wrap a callback in a Promise, but that is going to be overkill here because mongoose already provides a way to return a Promise -- just omit the callback entirely.

resolve(parent, args) {
  return Author.findOne({name: parent.authorName)
}

Your mutation resolver works because you return the value returned by calling save(), which actually returns a Promise that will resolve to the value of the model instance being saved.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183