assignment.coffee | |
---|---|
Mass Assignment for Model. In this example we'll discover how to define attribute types, and protect some of them from mass assignment. | Model = require 'mongo-model' |
Enabling optional synchronous mode. | require 'mongo-model/lib/sync'
sync = -> |
Connecting to default database and clearing it before starting. | db = Model.db()
db.clear() |
Let's define User. | class global.User extends Model |
By defautl there's no any types and You can assign anything to
any attribute using the | user = new User()
user.set name: 'Gordon Freeman', age: '28'
assert [user.name, user.age], ['Gordon Freeman', '28'] |
In previous example the Note also that all such helpers also available in the following form: | User.accessible 'age', Number
User.accessible 'name' |
If You need to set attributes from unsafe input with typecast You should
use This time String will be casted to Number before assigning it to the | user.safeSet name: 'Gordon Freeman', age: '28'
assert [user.name, user.age], ['Gordon Freeman', 28] |
There are also sensitive attributes that shouldn't be allowed to
update in mass assignment. Let's add the Actually there's no need to explicitly specify that attribute is protected,
if You don't make it If we try to to change | user.safeSet password: 'Black Mesa'
assert user.password, undefined |
You still can forcefully assign any attribute if You want. | user.set password: 'Black Mesa'
assert user.password, 'Black Mesa' |
Closing connection. | db.close() |
This stuff needed for synchronous mode. | Fiber(sync).run()
global.assert = (args...) -> require('assert').deepEqual args... |
In this example we covered mass assignment, attribute types and attribute protection. | |