简体   繁体   English

具有特定值的Mongoose模式属性

[英]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? 我的目标是定义角色属性以具有特定值('admin','member','guest'等等),实现这一目标的更好方法是什么? Thanks in advance! 提前致谢!

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. 另一种可能性是让userSchema具有一个构造函数,可以轻松地选择其中一个内置值。 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 更多: http//pivotallabs.com/users/pjaros/blog/articles/1368-javascript-constructors-prototypes-and-the-new-keyword

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM