Reputation: 24116
This is my 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 my Tweet
model:
import mongoose, { Schema } from 'mongoose';
const TweetSchema = new Schema({
text: {
type: String,
minLength: [5, 'Your tweet is too short.'],
maxLength: [144, 'Your tweet is too 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 is served by express like this:
import { graphqlExpress } from 'apollo-server-express';
import { makeExecutableSchema } from 'graphql-tools';
import typeDefs from '../graphql/schema';
import resolvers from '../graphql/resolvers';
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
const app = express();
app.use(
'/graphql',
graphqlExpress(req => ({
schema
}))
);
I use the following code to mock up some users and tweet using faker like this:
https://pastebin.com/raw/kJ9m8KjR
When the whole thing runs, I can see the mongodb is populated with dummy tweets linked to a user like this:
but when I query this via GraphiQL, the user info is not coming through:
Any ideas?
Upvotes: 1
Views: 850
Reputation: 84857
Your resolver gets the Tweets like this:
Tweet.find({}).sort({ createdAt: -1 });
If you check out the docs, you'll notice you need to tell mongoose to replace the id reference with an actual document by using populate:
Tweet.find({}).populate('user').sort({ createdAt: -1 });
Upvotes: 2