简体   繁体   中英

How do I accept an array of strings using Apollo Server and GQL?

I currently have a typeDefs file that has a custom Books type. This is how it looks at the moment:

type: Books {
   bookId: String
   authors: [String]
   description: String
   title: String
}

I am using MongoDB in order to store my data. My model looks like this:

const bookSchema = new Schema({
  authors: [
    {
      type: String,
    },
  ],
  description: {
    type: String,
    required: true,
  },
  // saved book id from GoogleBooks
  bookId: {
    type: String,
    required: true,
  },
  title: {
    type: String,
    required: true,
  }
});

And my resolvers look like this:

saveBook: async (parent, args, context) => {
            if (context.user) {
                const book = await Book.create({ ...args })

                await User.findByIdAndUpdate(
                    { _id: context.user._id },
                    { $addToSet: { savedBooks: { bookId: args.bookId } } },
                    { new: true }
                );

                return book;
            }

            throw new AuthenticationError('You need to be logged in!');
        }, 

When I use graphql playground and send data in the query variable I am getting an error that String cannot represent a non string value: [\"james\", \"jameson\"]", when I send

{
    "input": {
    "bookId": "1",
    "authors": ["james", "jameson"],
    "description": "thdfkdaslkfdklsaf",
    "title": "fdjsalkfj;a",
  }
}

I know that it is because I am using an array of strings and entering an array of strings to gql will result in this error. I thought that if I put brackets around the String in my typeDefs it would work just find. I can't seem to find a way to send an array of strings to gql. I looked through the documentation and can't find a way to complete this..

Make a typedef out of author and then give the author variable within books the type "Author".

I think you also have to define the array in the bookschema if I'm not incorrect.

And don't forget to make sure the model naming in your database has to be the same as in your code.

Like this:

type: Author {
   name: String
}

type: Books {
   bookId: String
   authors: [Author]
   description: String
   title: String
}
const bookSchema = new Schema({
  authors: [
    {
      type: Author,
    },
  ],
  description: {
    type: String,
    required: true,
  },
  // saved book id from GoogleBooks
  bookId: {
    type: String,
    required: true,
  },
  title: {
    type: String,
    required: true,
  }
});

Hope this works:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM