In MongoDB, there is no direct concept of foreign keys like in traditional relational databases. However, you can still implement relationships between collections and perform searches based on these relationships in GraphQL using a library like graphql-compose-mongoose or graphql-compose.

Let's consider an example where you have two MongoDB collections: Author and Book. Each book document has a reference to its author through an authorId field.

  1. Define Mongoose Models: First, define your Mongoose models for the Author and Book collections.

    javascript
    // author.model.js const mongoose = require('mongoose'); const authorSchema = new mongoose.Schema({ name: String, // Other author fields... }); module.exports = mongoose.model('Author', authorSchema);
    javascript
    // book.model.js const mongoose = require('mongoose'); const bookSchema = new mongoose.Schema({ title: String, authorId: { type: mongoose.Schema.Types.ObjectId, ref: 'Author', }, // Other book fields... }); module.exports = mongoose.model('Book', bookSchema);
  2. Define GraphQL Schema: Next, define your GraphQL schema using GraphQL types and resolvers. You can use graphql-compose-mongoose or graphql-compose to simplify this process.

    javascript
    const { composeWithMongoose } = require('graphql-compose-mongoose'); const { schemaComposer } = require('graphql-compose'); const Author = require('./path/to/author.model'); const Book = require('./path/to/book.model'); // Create GraphQL types from Mongoose models const AuthorTC = composeWithMongoose(Author); const BookTC = composeWithMongoose(Book); // Define relationships between types BookTC.addRelation('author', { resolver: () => AuthorTC.mongooseResolvers.findById(), prepareArgs: { _id: (source) => source.authorId, }, projection: { authorId: 1 }, }); // Define Query and Mutation fields schemaComposer.Query.addFields({ bookById: BookTC.mongooseResolvers.findById(), books: BookTC.mongooseResolvers.findMany(), }); // Define the Root GraphQL Schema const graphqlSchema = schemaComposer.buildSchema(); module.exports = graphqlSchema;
  3. Perform Search in GraphQL: With the GraphQL schema defined, you can now perform searches and fetch related data using GraphQL queries.

    graphql
    query { bookById(_id: "bookId") { title author { name } } }

    In this example, the query fetches a specific book by its _id and includes the author's name in the response.

By using GraphQL with MongoDB, you can establish relationships between collections and perform searches that retrieve related data. While MongoDB doesn't enforce foreign keys, the application logic can ensure the consistency and integrity of the data. The graphql-compose-mongoose or graphql-compose library provides helpful tools to simplify the process of defining the GraphQL schema and managing relationships between types.

Have questions or queries?
Get in Touch