0

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.

dplumbonline
  • 53
  • 1
  • 8
  • 1
    Does this answer your question? [Populate nested array in mongoose](https://stackoverflow.com/questions/19222520/populate-nested-array-in-mongoose) – Montgomery Watts Jul 31 '22 at 19:02
  • What is `new Schema`? That doesn't look like GraphQL – Bergi Jul 31 '22 at 21:06
  • @Bergi. The structure of the document. The model wraps around it. Best explanation with my limited knowledge. More info here - https://www.google.com/amp/s/www.freecodecamp.org/news/introduction-to-mongoose-for-mongodb-d2a7aa593c57/amp/ – dplumbonline Aug 02 '22 at 08:37

0 Answers0