I am trying to write a resolver which gets the accounts belonging to a customer. The parent.accounts
attribute is an array of account_id
s. In the code below, I attempt to get an array of accounts for each customer.
import Account from "../models/accounts.js";
import Customer from "../models/customers.js";
import { AccountInterface } from "../types/accounts.js";
import { CustomerInterface } from "../types/customers.js";
const resolvers = {
Query: {
// some other code
customers: async () => await Customer.find(),
},
Customer: {
accounts: async (parent: CustomerInterface) => {
const response = await Account.find()
.where("account_id")
.in(parent.accounts);
return response;
},
},
};
export default resolvers;
The code runs and returns the expected output. The problem is that it is too slow since the resolver queries the database for each element in the parents.accounts
array and it becomes increasingly slow when performing ‘get all’ requests from the db.
Is there a better way to write resolvers for nested queries? and if yes, how?