Express-graphql "Cannot read property 'collection' of undefined" with mongodb 同时运行突变和查询

Express-graphql "Cannot read property 'collection' of undefined" with mongodb while runing mutation & query

我正在尝试使用 express-graphql、node 和 mongodb 在图 QL 中查询和突变。对于查询和突变,我得到 "Cannot read property 'collection' of undefined"。我进入数据库,那里有一个包含文档的集合。上下文用于稍后添加身份验证。在过去的 2 天里,我尝试了多种命名集合的变体,但都没有成功。我需要声明一个常量吗?我错过了什么?

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)

mongoDB.js 导出 return 的函数是一个 Promise,但该 Promise 解析为 undefined 因为 console.log return 未定义。由于 connect 应该解析为调用它的 Mongoose 实例的值,因此要么完全删除 then 调用,要么确保 return 是 Mongoose 实例在里面。