简体   繁体   中英

mongoose, graphQL query returning null data though exist in mongo

I am trying to use a query in NodeJS using mongoose + GraphQL.

The model file as:

const mongoose = require('mongoose')
mongoose.set('debug', true);
const Schema = mongoose.Schema 

const authorSchema = new Schema({
    name: String,
    age: Number,
    authorId: String,
})

module.exports = mongoose.model('Author', authorSchema)

Schema for author is as below:

const AuthorType = new GraphQLObjectType({
    name: 'Author',
    fields: () => ({
        authorId: {type: GraphQLString},
        name: {type: GraphQLString},
        age: {type: GraphQLInt},
        books: {
            type: new GraphQLList(BookType),
            resolve(parent, args) {
                return book.find({authorId: parent.authorId})
            }
        },

    })
})

The rootQuery:

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        author: {
            type: AuthorType,
            args: {authorId: {type: GraphQLString}},
            resolve(parent, args){
                console.log("Author parent", parent, args)
                return Author.find({authorId: args.authorId})
            }
        },

Now when I am trying to use query from graphiQL using authorId, it returns as null, I have enabled mongoose debug, I see that mongoose sending correct query.

{
  author(authorId: "1") {
    name
    age
    authorId
  }
}

It returns below

{
  "data": {
    "author": {
      "name": null,   <<<<
      "age": null,   <<<
      "authorId": null   <<<
    }
  }
}

But I see that in mongoose log, it sends correctly

Mongoose: authors.find({ authorId: '1' }, { projection: {} })

In my mongo db, I have the data for authorId as below:

Atlas atlas-5p0amv-shard-0 [primary] test> db.authors.find({authorId: '1'})
[
  {
    _id: ObjectId("63adf57d50ee6abd7cce79ad"),
    name: 'Author1',
    age: 44,
    authorId: '1',
    __v: 0
  }
]
Atlas atlas-5p0amv-shard-0 [primary] test> 

Can you please let me know where I am doing wrong.

Thanks in advance.

With Regards, -M-

As per the comment above, you want Author.findOne not Author.find since you'd want a single document, not an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM