我用mongodb在graphql服务器和nodejs中编写了一个简单的代码,我的数据库有2个集合。明星和电影。当我运行此查询以向我展示所有电影时,我的GraphQL NodeJS服务器收到以下错误: “ MovieType.year的类型必须为Output Type,但得到:未定义。”
这是我的模式:
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLNonNull,
GraphQLList
} = require("graphql");
const {Movie, User} = require('/home/fateme/imdb_final/db')
const starType = new GraphQLObjectType({
name: "UserType",
fields: {
name: {
type: GraphQLString,
async resolve(objId) {
const starFind = await User.findOne({ _id: objId._id})
return starFind.name
}
},
imdbId: {
type: GraphQLString,
async resolve(objId) {
const starFind = await User.findOne({ _id: objId._id})
return starFind.imdbId
}
}
}
});
const movieType = new GraphQLObjectType({
name: "MovieType",
fields: {
title: {
type: GraphQLString,
async resolve(objId) {
const movieFind = await Movie.findOne({ _id: objId._id})
return movieFind.title
}
},
year: {
type: GraphQLInt,
async resolve(objId) {
const movieFind = await Movie.findOne({ _id: objId._id})
return movieFind.year
}
},
rate: {
type: GraphQLInt,
async resolve(objId) {
const movieFind = await Movie.findOne({ _id: objId._id})
return movieFind.rating
}
},
year: {
rate: GraphQLInt,
async resolve(objId) {
const movieFind = await Movie.findOne({ _id: objId._id})
return movieFind.year
}
},
director: {
type: GraphQLString,
async resolve(objId) {
const movieFind = await Movie.findOne({ _id: objId._id})
return movieFind.director
}
},
}
});
const queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
users: {
type: GraphQLList(starType),
async resolve() {
const allStar = await User.find({})
return allStar
}
},
movies: {
type: GraphQLList(movieType),
async resolve() {
const allMovie = await Movie.find({})
console.log(allMovie)
return allMovie
}
},
})
});
const schema = new GraphQLSchema({
query: queryType
});
module.exports = schema;
答案 0 :(得分:0)
如错误所示,您尚未为year
字段定义类型。相反,您不小心添加了rate
字段:
year: {
rate: GraphQLInt, // <-- here
async resolve(objId) {
const movieFind = await Movie.findOne({ _id: objId._id})
return movieFind.year
}
},
只需将rate
更改为type
,您就会很高兴:)