Apollo Resolver With Populate

Example 1 : Booking


bookingSchema = new mongoose.Schema({
	provider_id: mongoose.Types.ObjectId,
    service_id: mongoose.Types.ObjectId,
	.....
	pay: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Payment' }]
})

bookingResolver


Booking: {
	pay:catchAsync(async (booking, args, {models}) => {
		const book = await booking.populate('pay').execPopulate()
		return book.pay
	})
}

Example 2: Service


const serviceSchema = new mongoose.Schema(
  {
  ....
  payments: {
      service_price: Number,
      deposit: Number,
      taxable: Boolean,
      require_payment_for_service: Boolean,
      status: Boolean,
      pay: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Payment' }]
    },
	providers: [
      {
        id: String,
        name: String,
        status:Boolean
      }        
    ]
})

Service Resolver


Service: {
        payments: catchAsync(async (payments, args, { models }) => {
            const serv = await payments.populate('payments.pay').execPopulate()
            return serv.payments
        })
    }

Example 3 : Payment


const paymentSchema = new mongoose.Schema({
    service_id: String,
    appointment_id : String,
    payment_id : String,    
    transaction_id : String,
    customer_id : String,
	.....
})

Resolver


addPayment: async (parent, args, { models }) => {
	newPayment = await newPayment.save();
	if (newPayment) {
		const services = await models.Service.updateOne(
			{ _id: args.service_id },
			{
				$push: { "payments.payment": newPayment._id }
			},
			{}
		)
		const booking = await models.Booking.updateOne(
			{ _id: args.appointment_id },
			{
				$push: { "pay": newPayment._id }
			},
			{}
		)
		return newPayment;
	}
}

Sample


addPayment(
    	service_id:"5fae61203359694390d75a24",
        appointment_id: "5f854358de371a0a4c177018",
        payment_method: "Stripe",
        payment_type: 2,
        payment_id: "5456446",
        subscription_type: 2,
        transaction_id: "kjsjhdfsdf564654656",
        customer_id: "HKLDs554546",
        billing_cycle:  "12-10-2021 00:02:05",
        billing_frequency: "monthly",
        billing_address: {
            billing_name: "Ramesh kumar"            
        },
    status:true
    )
  {
    appointment_id,
    customer_id
    payment_method
  }



Reference

Mongoose’s Model.Populate()
How to use Populate in Mongoose & Node.js
Populate Subdocument in GraphQL
Nesting GraphQL With MongoDB
How to Create a Secure Node.js GraphQL API
API Reference: graphql-tools
GraphQL Express Apollo Server Setup
MongoDB relationships between documents
What is GraphQL?
Subscriptions

Leave a Reply

Your email address will not be published. Required fields are marked *