【发布时间】:2019-12-09 13:49:51
【问题描述】:
我正在尝试使用 node 和 mongoose 将 rest 后端转换为使用 GraphQL,但我不知道如何在 graphql 架构中表示类似于 mongoose 架构的 objectID 数组的东西。我的疑问,我如何让这个想法成为章节 ObjectIds 的列表?没找到类似的
猫鼬模式
const mongoose = require('../database/db')
const BookSchema = new mongoose.Schema({
name: {
type: String,
require: true,
},
author: {
type: String
},
sinopsis: {
type: String
},
chapters:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'Chapter'
}],
}, {
timestamps: true,
})
const ChapterSchema = new mongoose.Schema({
name: {
type: String
},
number: {
type:Number
},
content: {
type: String
},
}, {
timestamps: true,
})
const Chapter = mongoose.model('Chapter', ChapterSchema)
const Book = mongoose.model('Book', BookSchema)
module.exports.Book = Book
module.exports.Chapter = Chapter
GraphQL 架构:
type Book {
id: ID!
name: String!
author: String
sinopsis: String
chapters: [ID] (here is my doubt, how do i make this think be a list of Chapter ObjectIds)
}
type Chapter {
id: ID!
name: String!
number: String!
content: String!
}
type Query{
books: [Book!]!
book(id: ID!): Book
bookChapters(id: ID!): [ID]
chapter(id: ID!): Chapter!
}
type Mutation {
createBook(name: String!, author: String!,
sinopsis: String!, chapters: [ID!]): Book
createChapter(name: String!, number:String!,
content:String!): Chapter
}
这是我得到的错误。
{
"error": {
"errors": [
{
"message": "Field \"chapters\" must not have a selection since type \"[ID]\" has no subfields.",
"locations": [
{
"line": 3,
"column": 14
}
]
}
]
}
}
BookResolver.js
const db = require('../models/Book')
module.exports = {
Query:{
books: () => db.Book.find(),
book: (_,{id}) => db.Book.findById(id),
bookChapters: (_,{id}) => {
const book = db.Book.findById(id)
/* console.log(book + "aaa") */
const chapterlist = db.Chapter.find(book)
return chapterlist
},
chapter: (_,{id}) => db.Chapter.findById(id),
},
Mutation:{
createBook: (_, {name, author, sinopsis}) => db.Book.create({name, author, sinopsis}),
createChapter: (_, {name, number, content }) => {
db.Chapter.create({name, number, content})
},
},
}
【问题讨论】:
-
您的 GraphQL 架构很好。正如您所拥有的,它将返回一个 ID 数组,该数组将被序列化为字符串。您看到的错误与您查询架构的方式有关,而不是与架构本身有关。如果一个字段返回一个标量或一个标量列表,它不会有额外的子字段(即您不能在
chapters下请求额外的字段,因为没有字段) -
哦,谢谢你的回复,我会运行一些测试,看看我是否可以让这个查询工作我得到你所说的所以我会尝试修复它
标签: node.js graphql mongoose-schema