出现这个错误通常是因为没有在Model中定义需要查询的字段。解决方法是定义需要查询的字段,例如在mongoose中,可以使用findById
而不是findOneById
。以下是一个示例代码:
const { ApolloServer } = require('apollo-server-express');
const mongoose = require('mongoose');
// 定义schema
const typeDefs = `
type User {
id: ID!
name: String!
email: String!
}
type Query {
user(id: ID!): User
}
`;
// 定义resolvers
const resolvers = {
Query: {
user: async (parent, args) => {
const { id } = args;
const User = mongoose.model('User');
const user = await User.findById(id);
return user;
}
}
};
// 创建服务器
const server = new ApolloServer({ typeDefs, resolvers });