Loading relational data in GraphQL & MongoDB -
this schema:
type user { _id: id! username: string email: string! firstname: string lastname: string avatar: string createdat: date! updatedat: date! } type tweet { _id: id! text: string! user: user! favoritecount: int! createdat: date! updatedat: date! }
and here's tweet
model:
import mongoose, { schema } 'mongoose'; const tweetschema = new schema({ text: { type: string, minlength: [5, 'your tweet short.'], maxlength: [144, 'your tweet long.'] }, user: { type: schema.types.objectid, ref: 'user' }, favoritecount: { type: number, default: 0 } }, { timestamps: true }); export default mongoose.model('tweet', tweetschema);
the above graphql schema served express this:
import { graphqlexpress } 'apollo-server-express'; import { makeexecutableschema } 'graphql-tools'; import typedefs '../graphql/schema'; import resolvers '../graphql/resolvers'; const schema = makeexecutableschema({ typedefs, resolvers }); const app = express(); app.use( '/graphql', graphqlexpress(req => ({ schema })) );
i use following code mock users , tweet using faker this:
https://pastebin.com/raw/kj9m8kjr
when whole thing runs, can see mongodb populated dummy tweets linked user this:
but when query via graphiql, user info not coming through:
any ideas?
your resolver gets tweets this:
tweet.find({}).sort({ createdat: -1 });
if check out docs, you'll notice need tell mongoose replace id reference actual document using populate:
tweet.find({}).populate('user').sort({ createdat: -1 });
Comments
Post a Comment