Wolf_Tru
Wolf_Tru

Reputation: 563

How do I setup a member roles for a Users schema using mongoose

I'm trying to figure out how to set up a user schema with members, admin, user, a guest. This is what thinking, but is it a conventional way of doing so? I'm having trouble finding a good resource for learning how to do this.

const UserSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  role: {
    type: [
      {
        type: String,
        enum: ["user", "admin"],
        default: ["user"]
      }
     ]
   },
   email: {
     type: String,
     required: true
   },
   password: {
     type: String,
     required: true
   },
   date: {
     type: Date,
     default: Date.now
   }
  });

Upvotes: 0

Views: 1247

Answers (1)

Akrion
Akrion

Reputation: 18525

What you would want to do is to start with the smallest set of the properties you would need which is shared among the 3 model types (guest, user, admin) and that would be your base schema.

Then using Mongoose descriminators (mongoose schema inheritance) you would inherit from it and decorate with more properties you level model.

For example your guest might not have a role property since he is a guest. So you might want to start with a base model of guest and add on top of it other props needed for the user/admin.

Example:

var options = {discriminatorKey: 'type'};

var guestSchema = new mongoose.Schema({
  date: { type: Date, default: Date.now },
  username: { type: string, default: 'guest_' + Date.now },
}, options);

var Guest = mongoose.model('Guest', guestSchema);

var User = Guest.discriminator('User',
  new mongoose.Schema({password: String}, options));

// Now you have Guest as base model and User with decorated 'password' field

You can read the official documentation on this here

There are also plenty of articles online on the subject.

Upvotes: 1

Related Questions