我正在尝试使用express-graphql、node和mongodb查询图QL中的突变。对于查询和突变,我都得到了“无法读取未定义的属性‘集合’”。我进入数据库,里面有一个包含文档的集合。上下文将在后面添加auth。在过去的两天里,我尝试了多种不同的命名方式,但都没有成功。我需要声明一个const吗?我遗漏了什么?
Server.js
const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./graphql/schema')
const mongoose1 = require('./mongoDB')
const expressPlayground = require('graphql-playground-middleware-express').default;
const cors = require('cors')
const Event = require('./models/events')
const app = express();
app.use(cors())
app.use(express.json());
// DB
const context = async () => {
const db = await mongoose1;
return { db };
};
// Provide resolver functions for your schema fields
const resolvers = {
events: async (_, context) => {
const { db } = await context();
return db
.collection('events')
.find()
.toArray();
},
event: async ({ _id }, context) => {
const { db } = await context();
return db.collection('events').findOne({ _id });
},
createEvent: args => {
const event = new Event({
title: args.eventInput.title,
description: args.eventInput.description,
})
return event.save().then(res => {
console.log(res);
return { ...res._doc }
}).catch(err => {
console.log(err)
throw err
});
}
}
app.use(
"/graphql",
graphqlHTTP({
schema,
rootValue: resolvers,
context,
})
);
app.get('/playground', expressPlayground({ endpoint: '/graphql' }))
app.listen(5000);
console.log(`? Server ready at http://localhost:5000/graphql`);
数据库
require('dotenv').config()
const mongoose = require('mongoose');
const db = process.env.MONGODB
const mongoose1 = mongoose
.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
module.exports = mongoose1
模式
const { buildSchema } = require('graphql');
// Construct Schema
const schema = buildSchema(`
type Event {
_id: ID!
title: String!
description: String
date: String
}
input EventInput {
title: String!
description: String
date: String
}
type Query {
events: [Event!]!
event(_id: String!): Event!
}
type Mutation {
createEvent(eventInput: EventInput): Event
}
`);
module.exports = schema
模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const eventSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Event', eventSchema)
发布于 2020-01-19 01:47:41
mongoDB.js
导出的函数返回一个Promise,但该Promise解析为undefined
,因为console.log
返回未定义。由于connect
应该解析为调用它的Mongoose
实例的值,因此要么完全删除then
调用,要么确保返回其中的Mongoose
实例。
https://stackoverflow.com/questions/59802334
复制相似问题