将mongodb模型连接到apollo-server 2.0

时间:2018-08-12 01:09:59

标签: mongodb graphql apollo-server

我正在跟踪一个教程,该教程将mongo数据库与graphql一起使用,目前辅导教师使用apollo-server v1,但我使用的是apollo-server v2,我遇到的问题是如何将模型连接到graphql ,

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config({ path: "variables.env" });
const Recipe = require("./models/Recipe");
const User = require("./models/User");

// Bring in GraphQL-Express middleware
const { graphiqlExpress, graphqlExpress } = require("apollo-server-express");
const { makeExecutableSchema } = require("graphql-tools");

const { typeDefs } = require("./schema");
const { resolvers } = require("./resolvers");

// Create schema
const schema = makeExecutableSchema({
  typeDefs,
  resolvers
});

// Connects to database
mongoose
  .connect(process.env.MONGO_URI)
  .then(() => console.log("DB connected"))
  .catch(err => console.error(err));

// Initializes application
const app = express();

const corsOptions = {
  origin: "http://localhost:3000",
  credentials: true
};
app.use(cors(corsOptions));

// Create GraphiQL application
app.use("/graphiql", graphiqlExpress({ endpointURL: "/graphql" }));

// Connect schemas with GraphQL
app.use(
  "/graphql",
  bodyParser.json(),
  graphqlExpress({
    schema,
    context: {
      Recipe,
      User
    }
  })
);

const PORT = process.env.PORT || 4444;

app.listen(PORT, () => {
  console.log(`Server listening on PORT ${PORT}`);
});

因此,在apollo-server v1中,您在graphqlExpress中传递了mongo模式(模型)

 Connect schemas with GraphQL
    app.use(
      "/graphql",
      bodyParser.json(),
      graphqlExpress({
        schema,
        context: {
          Recipe,
          User
        }
      })
    );

但是在v2中,您不再使用graphqlExpress函数,

https://www.apollographql.com/docs/apollo-server/v2/migration-two-dot.html

那么我如何/在哪里传递数据库模型?

目前我有这个

const express = require ('express')
const mongoose = require ('mongoose')
const { ApolloServer } = require('apollo-server-express');

require('dotenv').config({path: 'variables.env'})

// mongo schemas/models
const Recipe = require('./models/Recipe')
const User = require('./models/User')

//Graphql schema
const {typeDefs} = require('./schema')
const {resolvers} = require('./resolvers')

// connects to database
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true} )
.then(()=> console.log('DB connected'))
.catch(error => console.log(error))

const PORT = process.env.PORT || 4444;

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.listen({ port: PORT }, () =>
  console.log(` Server ready at http://localhost:${PORT}${server.graphqlPath}`)
)

2 个答案:

答案 0 :(得分:3)

如果想像以前一样,需要将context函数添加到ApolloServer初始化中:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => ({
    Recipe,
    User
  })
});

答案 1 :(得分:0)

example与PG完美搭配,如果您使用的是Mongo,只需将pg调用替换为猫鼬,您就可以使用了。