Search code examples
node.jsmongodbrestify

MongoDB Database design for different type of users


I'm making a RESTful API for a website where there are multiple type of users.

  • Admin
  • Vendors (Company name, address)
  • Regular Users (Name, phone)

The users will always be whatever they initially registered as (permanent specialization).

I'm using Mongoose and NodeJS, and I have come up with the following Model for User so that I can easily manage login with new Social websites in future.

{
  userType: { type: String, lowercase: true },
  contact: {
    email: { type: String, lowercase: true, index: { unique: true, sparse: true } }
  },
  accounts: {
    local: { password: String },
    facebook: { id: String, token: String }
  }
}

So my question is, since I have different type of users and each type has different profile information, where should I store information regarding each of them?

Make different models for each type and add a reference key in User model? Or is there a better way?


Solution

  • I don't think that putting this information in different collections is a good idea here. One of MongoDB's strengths is that you can put all relevant user information in a single document, so you can retrieve it with 1 query.

    I would add 3 fields to the user model:

    adminInfo: { ... },
    vendorInfo: { ... },
    userInfo: { ... },
    

    and fill the right one, depending on the user type. The other 2 fields can be null (or even not present at all).

    Don't go the normalisation route - it's not needed here.