title: How to achieve a one to many relationship with GraphQL & DataLoader
body: <p>I'm having a hard time figuring out why my graphQL &amp; DataLoader setup isn't working and could use some help.</p>
  
  <p>I have a User and a <code>Orchestra</code> type, and I would like to transform a <code>User</code> to populate its <code>createdOrchestras</code> field and do the same thing with Orchestra and an <code>owner</code> field.</p>
  
  <p><strong>EDITED</strong>. 
  The following code causes an infinite loop:</p>
  
  <p>Here are the DataLoaders, which are passed to the resolvers via context:</p>
  
  <pre class="lang-js prettyprint-override"><code>const DataLoader = require('dataloader');
  const Orchestra = require('../models/orchestras');
  const User = require('../models/users');
  
  const batchOrchestras = async ids =&gt; {
     const orchestras = await Orchestra.find({ _id: { $in: ids } });
  
     const orchestraMap = {};
     orchestras.forEach(o =&gt; {
        orchestraMap[o.id] = o;
     });
  
     return ids.map(id =&gt; orchestraMap[id] || new Error(`No result for ${id}`));
  }
  
  const batchUsers = async ids =&gt; {
     const users = await User.find({ _id: { $in: ids } });
  
     const userMap = {};
     users.forEach(u =&gt; {
       userMap[u.id] = u;
     });
  
     return ids.map(id =&gt; userMap[id] || new Error(`No result for ${id}`));
   };
  
  module.exports = () =&gt; new DataLoader(batchUsers) 
  module.exports = () =&gt; new DataLoader(batchOrchestras);
  </code></pre>
  
  <p>Here are the transform functions which should be capable of fetching data for nested fields via data loaders and modify sensitive fields like the user password.</p>
  
  <pre class="lang-js prettyprint-override"><code>async function transformUser(userId, loaders) {
    const user = await loaders.userLoader.load(userId.toString());
  
    return {
      ...user._doc,
      createdOrchestras: await Promise.all(
        user._doc.createdOrchestras.map(orchestra =&gt; 
          transformOrchestra(orchestra, loaders)
        )
      )
    }
  }
  
  async function transformOrchestra(orchestraId, loaders) {
    const orchestra = await loaders.orchestraLoader.load(orchestraId.toString());
  
    return {
      ...orchestra._doc,
      owner: transformUser(orchestra._doc.owner, loaders)
    }
  }
  
  module.exports = {
    transformUser,
    transformOrchestra
  }
  </code></pre>
  
  <p>How should I restructure the code to prevent an infinite loop but keeping the transform functions as the final providers of data for a particular field ?</p>