繁体   English   中英

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

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

我正在尝试使用 mongoose + GraphQL 在 NodeJS 中使用查询。

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)

作者的架构如下:

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})
            }
        },

    })
})

根查询:

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})
            }
        },

现在,当我尝试使用 authorId 从 graphiQL 使用查询时,它返回为 null,我启用了 mongoose 调试,我看到 mongoose 发送了正确的查询。

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

它在下面返回

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

但我看到在 mongoose 日志中,它发送正确

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

在我的 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> 

你能告诉我我哪里做错了吗?

提前致谢。

此致,-M-

根据上面的评论,您需要Author.findOne而不是Author.find ,因为您需要一个文档,而不是一个数组。

暂无
暂无

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

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