首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Express-graphql在运行突变和查询时无法使用mongodb读取未定义的属性‘集合’

Express-graphql在运行突变和查询时无法使用mongodb读取未定义的属性‘集合’
EN

Stack Overflow用户
提问于 2020-01-19 00:06:13
回答 1查看 325关注 0票数 0

我正在尝试使用express-graphql、node和mongodb查询图QL中的突变。对于查询和突变,我都得到了“无法读取未定义的属性‘集合’”。我进入数据库,里面有一个包含文档的集合。上下文将在后面添加auth。在过去的两天里,我尝试了多种不同的命名方式,但都没有成功。我需要声明一个const吗?我遗漏了什么?

Server.js

代码语言:javascript
运行
复制
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`); 

数据库

代码语言:javascript
运行
复制
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

模式

代码语言:javascript
运行
复制
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

模型

代码语言:javascript
运行
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-19 01:47:41

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59802334

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档