【问题标题】:Express-graphql "Cannot read property 'collection' of undefined" with mongodb while runing mutation & queryExpress-graphql“在运行突变和查询时无法使用 mongodb 读取未定义的属性‘集合’”
【发布时间】:2020-05-05 05:25:11
【问题描述】:

我正在尝试使用 express-graphql、node 和 mongodb 查询图 QL 中的突变。对于查询和突变,我得到“无法读取未定义的属性'集合'”。我进入数据库,那里有一个包含文档的集合。稍后可以在上下文中添加身份验证。在过去的两天里,我尝试了多种命名该系列的变体,但均未成功。我需要声明一个常量吗?我错过了什么?

服务器.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)

【问题讨论】:

    标签: node.js mongodb mongoose graphql express-graphql


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 2018-10-04
      • 1970-01-01
      • 2018-06-12
      • 2020-01-16
      • 2019-12-01
      • 1970-01-01
      • 2021-01-23
      • 2022-01-12
      相关资源
      最近更新 更多