Reputation: 611
I'm trying to connect apollo-server with my mongodb on mlab (I tried with my local mongo as well). I can connect to the db fine, although nothing is returned when testing with a graphql query. I just can't figure out how to actually get the data back from the db. I am using the latest apollo-server-express.
I've put this together from various tutorials and the docs but can't find a clear answer on my problem. Probably missing something very obvious.
Server.js
import express from 'express';
import { ApolloServer, gql } from 'apollo-server-express';
import Mongoose from 'mongoose';
import { Post } from './models/Post';
const app = express();
Mongoose.Promise = global.Promise;
Mongoose.connect('mongodb://<username>:<pw>@ds151282.mlab.com:51282/groupin', { useNewUrlParser: true })
.then(()=> console.log('DB connected'))
.catch(error => console.log(error))
const typeDefs = gql`
type Post {
title: String
description: String
author: String
url: String
}
type Query {
allPosts: [Post]
}
`;
const resolvers = {
Query: {
allPosts(parent, args) {
return Post.find({})
}
}
};
const apollo = new ApolloServer({
typeDefs,
resolvers,
context: ({req}) => ({ Post })
});
apollo.applyMiddleware({ app })
app.listen(4000, () => {
console.log(`🚀 Server ready at http://localhost:4000${apollo.graphqlPath}`);
});
Post.js
import Mongoose from 'mongoose';
const PostSchema = {
title: String,
description: String,
author: String,
url: String
};
const Post = Mongoose.model('Post', PostSchema);
export { Post };
Upvotes: 1
Views: 1217
Reputation: 609
Try to use mongoose Schema instead of plain object
Post.js
import Mongoose from 'mongoose';
const PostSchema = new Mongoose.Schema({
title: String,
description: String,
author: String,
url: String
});
const Post = Mongoose.model('Post', PostSchema);
export { Post };
Upvotes: 3