I want to query my server to return some data with GraphQL.
My relative models:
Users
const usersSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
minlength: 5
},
tags: [Tags.schema],
comments: [Comments.schema],
});
Tags
const tagsSchema = new Schema({
comments: [Comments.schema],
});
Comments
const commentsSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'Users',
required: true,
},
});
TypeDefs
type User {
_id: ID
username: String
}
type Tag {
_id: ID
comments: [ Comment ]
}
type Comment {
_id: ID
user: User
}
type Query {
tag( _id: ID ): Tag
}
Query
gql`query tag($_id: ID) {
tag(_id: $_id) {
_id
comments {
_id
user {
_id
username
}
}
}}`
Resolver
tag: async (parent, {_id}) => {
const tag = await Tags.findById(_id).populate('comments').populate('user');
return tag
}
Data returned
{
"_id": "62e3dd485f05b92e5f234b63",
"comments": [
{
"_id": "62e3ea0fc280583503f0006b",
"user": {
"_id": "62e3dd3e5f05b92e5f234b5f",
"username": null,
}
}
}
I'm after the username here.
If I query my comments independently, username fields will populate. If I query my tags the comments contain only the id of the user, with the username "null"
Thank you.