title: What's the best way of modeling mongoose/mongoDB database for saas
body: <p>I'm trying to model a Saas application in which I'll have different companies using the services. I'm a bit confused on best way of modelling my mongoose database for this type of service.</p>
  
  <p>So the model is something like</p>
  
  <pre><code>Company
    Name
    Users
      -&gt;Roles (Admin,editor etc)
    Projects
  </code></pre>
  
  <p>What's the best way of modeling such an application? </p>
  
  <p>Should i create different models for user, projects etc and attach the company unique ID to all those users or projects that are within that company. Also Referencing those users or projects in the company model as well. Something like </p>
  
  <pre><code>//User is used as a separate model and is only referenced in company schema
  var userSchema = new Schema({  
      Name  : String,
      Role: {
          type: String,
          enum: ['admin','reader', 'editor'],
          default: 'reader'
      },
      Company : { type: Schema.ObjectId, ref: 'Company' }
  });
  mongoose.model('User', userSchema);
  
  var companySchema = new Schema({  
      Name  : String,
      Users : [
           { type: Schema.ObjectId, ref: 'User' }
      ],
      Projects : [
           { type: Schema.ObjectId, ref: 'Project' }
      ]
  });
  
  mongoose.model('Company', companySchema);
  </code></pre>
  
  <p>Or</p>
  
  <p>Just referencing the user and project schemas in the company schema without having separate models</p>
  
  <pre><code>//userSchema is used as a child in company schema
  var userSchema = new Schema({  
      Name  : String,
      Role: {
          type: String,
          enum: ['admin','reader', 'editor'],
          default: 'reader'
      },
  });
  
  var companySchema = new Schema({  
      Name  : String,
      Users : [
          userSchema 
      ],
      Projects : [
          projectSchema 
      ]
  });
  
  mongoose.model('Company', companySchema);
  </code></pre>
  
  <p>Which is the best approach on the long run in terms of easily making queries for the sub-documents, memory allocation, public api exposure in future if required?</p>
  
  <p>And if its the second way then do i need to have id's or those subdocuments? Can i just use the unique company id for making queries and then finding the stuff needed once the relative company is found within the document? </p>