简体   繁体   English

mongoose、graphQL 查询返回 null 数据,尽管存在于 mongo 中

[英]mongoose, graphQL query returning null data though exist in mongo

I am trying to use a query in NodeJS using mongoose + GraphQL.我正在尝试使用 mongoose + GraphQL 在 NodeJS 中使用查询。

The model file as: model 文件为:

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.现在,当我尝试使用 authorId 从 graphiQL 使用查询时,它返回为 null,我启用了 mongoose 调试,我看到 mongoose 发送了正确的查询。

{
  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 日志中,它发送正确

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

In my mongo db, I have the data for authorId as below:在我的 mongo 数据库中,我有 authorId 的数据如下:

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-此致,-M-

As per the comment above, you want Author.findOne not Author.find since you'd want a single document, not an array.根据上面的评论,您需要Author.findOne而不是Author.find ,因为您需要一个文档,而不是一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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