dresende / node-orm2

Object Relational Mapping
http://github.com/dresende/node-orm2
MIT License
3.07k stars 376 forks source link

How to set a value to default within an array when setting a model? #719

Open CarlosAmaral opened 8 years ago

CarlosAmaral commented 8 years ago

In the role:

var User = db.define("user", { id: {type: 'serial', key: true, unique:true}, username: String, email: String, role:['normal', 'moderator', 'admin'] });

thank you

dxg commented 8 years ago

I'd use a basic string property, set defaultValue and use an inside list validator. I doubt it's possible using that shorthand syntax. I'm not even sure how that syntax works.

CarlosAmaral commented 8 years ago

@dxg So basically this -> role: {type:'enum',values:['normal','moderator','admin']} Can you shed some more light on this? Thank you

dxg commented 8 years ago

I strongly advise against using an enum unless you actually need the space savings that come with it.

var ROLES = [ 'pleb', 'duke', 'lord', 'king' ];

db.define('user',
  {
    role: { type: 'text', defaultValue: 'pleb',  required: true  }
  },
  validations: {
    role: orm.validators.insideList(ROLES, "Invalid role")
  }
);

Strings are a lot easier to work with, especially when you start adding new roles.

CarlosAmaral commented 8 years ago

Thanks for the input and code example! Much appreciated