Continuing from  the last post, I am going to write about populating subdocument in GraphQL.

Context

So, what I have done last time was building two schemas then I nested one of them in an array of another. To give you little more about context about this software, this is a POS software that there are a bunch of products and each payment has an array of products a customer paid.

// models/Transaction.js
import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const itemSchema = new Schema({
name: { type: String },
amount: { type: Number },
});

const transactionSchema = new Schema(
{
price: { type: Number },
method: { type: String, default: 'VISA' },
cardNumber: { type: String },
paidTime: { type: Date, default: new Date() },
items: [itemSchema], // we will change this part
}
);

export const Transaction = mongoose.model('Transaction', transactionSchema);

This time, I would build a completely new model and reference from it that will act as a foreign key.

Overview

What I am going to do is to save ids in an array, rather than store whole subdocument. From something like the left one to the right one.

Image for post

#graphql #mongodb #backend-development #nodejs

Populate Subdocument in GraphQL
19.05 GEEK