我正在与Node.js和MongoDB一起单独学习GraphQL,可以看到我的mongoDB与其中的users
集合相连,但是当我查询它时,总是在graphiQL UI中得到空数组或空数组。我不想将每个graphql类型和所有解析器放在一个文件中,因为当项目增长时,它将变得太复杂以至于无法调试。我一直在寻找其他人的做法,甚至尝试效法他们的榜样,但还是没有运气。
这是我的文件结构:
-server
-models
-user.js
-schema
-user
-userType.js
-usersResolver.js
-query.js
-schema.js
-index.js
我尝试将关键字context
放在expressGraphQL()
中,在我的usersResolver.js
中,我查找context
的内容,但是没有集合或数据库相关信息。或在我的usersResolver.js中,我只需要/ models / user中的用户架构并将其分配给变量,然后执行User.find()
,但仍然为空或为空。
我的index.js
mongoose.connect(keys.MONGO_URI, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => { console.log( '+++Connected to mongoose')})
app.use('/graphql', expressGraphQL({
schema,
graphiql: true,
pretty: true,
}))
我的models/user
const mongoose = require('mongoose');
const { Schema } = mongoose;
const userSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,
firstname: String,
lastname: String,
age: String,
companyId: String
}, { collection: 'users'})
module.exports = mongoose.model("users", userSchema)
我的/schema/query
:
const graphql = require('graphql');
const {
GraphQLObjectType,
GraphQLString,
GraphQLList,
} = graphql;
const UserType = require('./user/userType');
const UserResolver = require('./user/userResolver');
const UsersResolver = require('./user/usersResolver');
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: () => ({
user: {
type: UserType,
args: { id: { type: GraphQLString } },
resolve: UserResolver
},
users: {
type: new GraphQLList(UserType),
// resolve: UsersResolver
resolve: (users) => {
console.log("users: ", users)
return UsersResolver
}
}
})
})
module.exports = RootQuery;
我的usersResolver
:
const usersResolver = async(parentValue, args ) => {
const users = await UserModel.find().exec()
if(!users) {
console.log("here")
throw new Error('Error in usersResolver.js')
}
return users
}
module.exports = usersResolver;
我的schema
文件:
const graphql = require('graphql');
const RootQuery = require('./query');
// const mutation = require('')
const {
GraphQLSchema
} = graphql
module.exports = new GraphQLSchema({
query: RootQuery
})
我的userType
:
const graphql = require('graphql');
const {
GraphQLObjectType,
GraphQLNonNull,
GraphQLString,
GraphQLInt,
GraphQLID
} = graphql;
const UserCompanyResolver = require('./userCompanyResolver');
const UserType = new GraphQLObjectType({
name: 'User',
description: 'a user',
fields: () => ({
id: {
// type: new GraphQLNonNull(GraphQLString),
type: new GraphQLNonNull(GraphQLID),
description: 'ID associated with database'
},
firstname: {
type: GraphQLString
},
lastname: {
type: GraphQLString
},
age: {
type: GraphQLInt
},
company: {
type: require('../company/companyType'),
resolve: UserCompanyResolver
}
})
})
module.exports = UserType;
我应该能够以graphiQL UI的形式从MongoDB的所有用户文档获得响应,但是它始终是空数组。不知道我在哪里做错了,也不了解。
任何帮助将不胜感激。