mreaction:shadow-models

v0.1.1Published 10 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

shadow-model

This is a work in progress, better docs to come when its more stable.

Example

1Example = new ShadowModel({
2  //You must defined a collection object, currently it only takes Mongo, PRs welcome
3  //you could pass options, transforms are allowed but not needed
4  collection: new Mongo.Collection('example'), 
5  schema: { //See [shadow-schemas](https://github.com/Meteor-Reaction/shadow-schemas/)
6    name: {
7      validation: function (value) {
8        if (_.isString(value)) {
9          return this.valid('is valid')
10        } else {
11          return this.invalid('not valid')
12        }
13      },
14      default: 'name'
15    },
16    'foo.bar': {
17      validation: function (value) {
18        if (_.isString(value)) {
19          return this.valid('is valid')
20        } else {
21          return this.invalid('not valid')
22        }
23      },
24      default: 'in foo.bar'
25    },
26    'foo.var.bat': {
27      default: ['winning']
28    }
29  },
30  helpers: { //see [shadow-helpers](https://github.com/Meteor-Reaction/shadow-helpers)
31    a: 'a',
32    getNameWithCaps: function () {
33      console.log(this)
34      return this.name.toLocaleUpperCase();
35    }
36  },
37  foo: function (value) { //Model, collection, properties.
38    return 'foo: ' + value
39  }
40})
41
42//model
43Example.foo('test') //returns 'foo: test'
44
45//instance
46var obj = Example.new({name: 'other name'}) //not inserted, but comes with collection transform
47obj.getNameWithCaps() //returns 'OTHER NAME'
48obj.foo.bar //returns 'in foo.bar'
49obj.$validate() //returns an object with validity state
50var data = obj.$data() //get the schema defined properties without model logic
51//you could get the model wrapper back with Example.new(data)
52var id = Example.insert(data) //will run validations and throw an exception if it fails
53//updates work much like inserts
54var obj = Example.findOne(id) //data with model wrapper, with _id now.