title: Building Nested Maps in Mongoose DB
body: <p>I am trying to create a simple nested JSON structure for accounts. The accounts Map will hold keys related to the institution, for example "TD", then "TD" will be a map of key value pair for each account where the key will be the accountId. </p>
  
  <p>PS: I know that this could be also done with having a array instead of a map, but I am giving this example for simplicity as the question is more geared for how to handle any nested map structure like the following in Mongoose, or if its possible at all or any workarounds.</p>
  
  <p>An example of what the object would be: </p>
  
  <pre><code>accounts: {
  
   "TD": {
      "abcsd1234": {
        "name": "Chequing Account",
        "balance": 1224
       },
      "dsadv1234": {
        "name": "Savings Account",
        "balance": 22001
       }
      ...
    },
  
   "RBC": {
     ...
    }
   ...
  
  }
  
  </code></pre>
  
  <p>What I tried to do was have a schema setup like the following:</p>
  
  <pre><code>UserSchema = new mongoose.Schema({
   ... // other properties
  
   accounts: {
    type: Map
    of: AccountsSchema
   }
  
  ...
  })
  
  AccountsSchema = new mongoose.Schema({
   accounts: {
    type: Map, 
    of: BalanceSchema
   }
  })
  
  BalanceSchema = new mongoose.Schema({
   name: String,
   balance: Number
   ...
  })
  
  </code></pre>
  
  <p>Then when I wanted to access or change this schema I began to run into problems.</p>
  
  <p>An example of what I tried doing to access this setup was:</p>
  
  <pre><code>
  let institutionName = 'TD' // Would be dynamic
  let accountId =  'someId'
  let account = {..} // A BalanceSchema object
  
  user.accounts.set(institutionName, {accountId, account} 
  
  </code></pre>
  
  <p>This would make user.accounts.TD => {}. A empty map so the accounts isn't being populated in the map.</p>
  
  <p>I also tried to figure out if I could do something like </p>
  
  <pre><code>user.accounts.institutionName.set(accountId, account)
  
  </code></pre>
  
  <p>But institutionName is dynamic so I couldn't work it out.</p>
  
  <p>How can I set the items in the nested map properly with Mongoose? What is the best method for accessing, setting and working with maps that are nested multiple levels down?</p>
  
  <p>What are other work arounds to achieve similar use cases?</p>
  
  <p>Thanks.</p>