我正在尝试将apollo服务器与mlab上的mongodb连接(我也尝试了使用本地mongo)。我可以很好地连接到数据库,尽管在使用graphql查询进行测试时什么也没有返回。我只是不知道如何实际从数据库取回数据。我正在使用最新的apollo-server-express。
我从各种教程和文档中总结了这些内容,但是找不到关于我的问题的明确答案。可能缺少一些非常明显的东西。
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 };
答案 0 :(得分:1)
尝试使用猫鼬模式而不是普通对象
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 };