【问题标题】:Mongoose schema property with specific values具有特定值的 Mongoose 模式属性
【发布时间】:2012-10-28 08:40:09
【问题描述】:

这是我的代码:

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

我的目标是将角色属性定义为具有特定值(“admin”、“member”、“guest”等),有什么更好的方法来实现这一点?提前致谢!

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    你可以做枚举。

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

    【讨论】:

    • 不错,然后呢?当我想创建一个特定的用户? var jhon = 新用户(电子邮件:'jhon@gmail.com',密码:'samplepass',角色:?);
    • @cl0udw4lk3r 仍然只是一个字符串,例如role: 'admin'
    【解决方案2】:

    据我所知,没有一种方法可以为角色设置特定的值,但也许您想根据主对象类型创建多个对象类型,每个对象类型都有自己的角色(以及其他任何内容)你想区分)。比如……

    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
    

    另一种可能性是使用带有构造函数的 userSchema,该构造函数允许您轻松选择一个内置值。一个例子……

    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
    

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

    【讨论】:

    • 对不起,我担心你的回答不适合我的问题,我需要知道如何用 Mongoose.js 做到这一点,谢谢!
    猜你喜欢
    • 2014-12-28
    • 2016-01-23
    • 2019-08-12
    • 2021-05-24
    • 2020-06-08
    • 2019-09-13
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多