Search⌘ K
AI Features

Updating our Schema

Explore how to update your MongoDB schema for Book, Author, and Review collections while managing relationships via authorId and reviewIds. Learn to define detailed GraphQL queries and mutations, implement resolvers with TypeScript using MongoDB driver methods, and test your GraphQL endpoint integrated with MongoDB in a Deno application.

Schema types and inputs

Our MongoDB database has three entities: Book, Author, and Review. Let’s consider the following schema:

C++
const types = gql`
type Book {
_id: String
title: String
price: Float
identifier: String
description: String
author: Author
reviews: [Review]
}
type SimpleBook {
_id: String
title: String
price: Float
identifier: String
description: String
}
type Author {
_id: String
firstName: String
lastName: String
}
type Review {
_id: String
bookId: String
rating: Int
comment: String
}
`;

MongoDB schema

To access our database, we will need to define our schema as follows (they can be different from the GrapghQL ones):

TypeScript 3.3.4
// Defining schema interface
interface BookSchema {
_id: Bson.ObjectId;
title: string;
price: number;
identifier: string;
description: string;
authorId: Bson.ObjectId;
reviewIds: Bson.ObjectId[];
}
interface AuthorSchema {
_id: Bson.ObjectId;
firstName: string;
lastName: string;
}
interface ReviewSchema {
_id: Bson.ObjectId;
rating: number;
comment: string;
bookId: string;
}

In the schema definition given above, we try to use different approaches when handling the relationship between entities. It’s important to note the following:

  • authorId is a field in the book schema used to reference the author of the book.
  • reviewIds is an array of review
...