簡體   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