Mongoose schema property with specific values

Here's my code:

var userSchema = new mongoose.Schema({
  email: String,
  password: String,
  role: Something
});

My goal is to define the role property to have specific values ('admin', 'member', 'guest' and so on..), what's the better way to achieve this? Thanks in advance!

Answers


You can do enum.

var userSchema = new mongoose.Schema({
  // ...
  , role: { type: String, enum: ['admin', 'guest'] }
}

var user = new User({
 // ...
 , role: 'admin'
});

There isn't really a way that I know of to have specific values possible for role, but maybe you'd like to create multiple object types based off of a master object type, each with their own roles (and anything else you want to distinguish). For example...

var userSchema = function userSchema() {};
userSchema.prototype = {
  email: String,
  password: String,
  role: undefined
}
var member = function member() {};
member.prototype = new userSchema();
member.prototype.role = 'member';

var notSupposedToBeUsed = new userSchema();
var billTheMember = new member();
console.log(notSupposedToBeUsed.role); // undefined
console.log(billTheMember.role); // member

Another possibility is have userSchema with a constructor that easily allows you to select one of the built in values. An example...

var userSchema = function userSchema(role) {
    this.role = this.role[role];
    // Gets the value in userSchema.role based off of the parameter
};
userSchema.prototype = {
  email: String,
  password: String,
  role: { admin: 'admin', member: 'member', guest: 'guest' }
}
var a = new userSchema('admin');
var b = new userSchema('blah');
console.log(a.role); // 'admin'
console.log(b.role); // undefined

More: http://pivotallabs.com/users/pjaros/blog/articles/1368-javascript-constructors-prototypes-and-the-new-keyword


Need Your Help

Android build gradle is too slow (Dependency Resolution)

android android-studio gradle android-gradle build.gradle

I've been working with Android Studio (my current version 1.5) for 2 years. Everything was OK, but when I downloaded Canary (2.1 p5), everything went wrong. Every time I want to create a new projec...

PHP Fatal error: Call to undefined function json_decode()

php json apache ubuntu

Apache is logging PHP Fatal error: Call to undefined function json_decode(). After some googling, it seems this problem is a result of not having the latest version of php. Oddly, running php --ve...