我只是从graphql开始,在操场上调用基本查询时遇到了一些问题。
我有一个server.js
const mongoose = require('mongoose');
require('dotenv').config({ path: 'variables.env' })
const { ApolloServer } = require('apollo-server')
//Monogoose schemas
const Recipe = require('./models/Recipe');
const { typeDefs } = require('./schema');
const { resolvers } = require('./resolvers')
const server = new ApolloServer({
typeDefs,
resolvers
})
// Connect to DB
mongoose
.connect(process.env.MONGO_URI, { autoIndex: false })
.then(() => {
console.log('DB connected')
})
.catch(err => console.error(err))
server.listen().then(({ url }) => {
console.log(`server listening on ${url}`)
})
一个schema.js
const gql = require('graphql-tag');
exports.typeDefs = gql`
type Recipe{
_id: ID
name: String!
category: String!
description: String!
instructions: String!
createdDate: String
likes: Int
username: String
}
type Query {
getAllRecipes: [Recipe]
}
`
resolvers.js
exports.resolvers = {
Query: {
getAllRecipes: async (root, args, { Recipe }) => {
const allRecipes = await Recipe.find()
return allRecipes
}
},
和猫鼬模式
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const RecipeSchema = new Schema({
name: {
type: String,
required: true
},
category: {
type: String,
required: true
},
description: {
type: String,
required: true
},
instructions: {
type: String,
required: true
},
createdDate: {
type: Date,
default: Date.now
},
likes: {
type: Number,
default: 0
},
username: {
type: String
}
})
module.exports = mongoose.model('Recipe', RecipeSchema)
服务器和数据库的连接正常工作,当我打开操场时,将显示架构。我数据库中有数据
当我运行查询时:
query{
getAllRecipes{
name
}
}
我收到一个错误"Cannot read property 'find' of undefined",
谁能在这里看到我在做什么错
答案 0 :(得分:1)
在您的resolvers.js
文件上,您期望Recipe
来自context
参数,但是您没有将其添加到我从摘录中得知的任何地方。
在初始化ApolloServer实例期间,您可以传递一个context
属性,该属性将注入到所有解析程序中:
...
const server = new ApolloServer({
typeDefs,
resolvers,
context: {
Recipe,
},
});
context
属性也可以是一个函数,该函数可以在最后返回一个对象,以防您需要进一步详细说明。
有关该选项以及您可以通过的其他选项的更多详细信息,请参见:https://www.apollographql.com/docs/apollo-server/api/apollo-server/。