Mongoose schema property with specific values

Here is my code:

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

My goal is to define a role property in order to have specific values ​​("admin", "member", "guest", etc.), what is the best way to achieve this? Thanks in advance!

+7
source share
2 answers

You can do the listing.

 var userSchema = new mongoose.Schema({ // ... , role: { type: String, enum: ['admin', 'guest'] } } var user = new User({ // ... , role: 'admin' }); 
+20
source

There really is no way that I could have specific values ​​for the role, but maybe you need to create several types of objects based on the type of the main object, each with its own roles (and something 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 to have userSchema with a constructor that easily allows you to select one of the built-in values. 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 details: http://pivotallabs.com/users/pjaros/blog/articles/1368-javascript-constructors-prototypes-and-the-new-keyword

0
source

All Articles