Mongo Model

Domain Model for MongoDB and Node.JS

CoffeeScript and Fibers are optional.


You can use Model with plain old JavaScript and Callbacks.

Defining Model

class global.Post extends Model
  @collection 'posts'
  @embedded   'comments'

class global.Comment extends Model
  

CRUD

Dynamic schema, flexible queries.

CRUD

post = new Post
  text: 'Zerg on Tarsonis!'

post.comments.push new Comment
  text: "Can't believe it!"

post.save()
  

CRUD

Post.first(status: 'published')

Post.
  find(status: 'published').
  sort(createdAt: -1).
  limit(25).
  all()
  

CRUD with Scopes

class global.Post extends Model
  @latest: ->
    @find(status: 'published').
    @sort(createdAt: -1).
    @limit(25)

Post.latest().paginate(params).all()
  

CRUD

post = Post.first()

post.comments.push new Comment
  text: 'Sad news ...'

post.save()
  

CRUD with Modifiers

post = Post.first()
post.update $set:
  title: 'Striking news!'

Post.update {_id: postId}, $set:
  title: 'Striking news!'
  

CRUD

post.delete()

Post.delete status: 'draft'
  

Associations

1-to-1, 1-to-N, N-to-M

Associations

class global.Post extends Model
  comments: ->
    Comment.find postId: @_id

class global.Comment extends Model
  post: ->
    Post.first _id: @postId
  

Associations CRUD

post = Post.create
  text: 'Zerg found on Tarsonis!'

post.comments().create
  text: "Can't believe it!"
  

Associations CRUD

post = Post.first()

post.comments().limit(25).all()
post.comments().count()
  

Callbacks

before / after of create, update, validate and delete.

Callbacks

class global.Post extends Model
  @after 'delete', (callback) ->
    @comments().delete callback
  

Validations

Use errors to store messages, valid to check and validate to define rules.

Validations

class global.Post extends Model
  @validate (callback) ->
    unless @text
      @errors.add
        text: "can't be empty"
    callback()
  

Callbacks and Validations also works on Embedded Models


If You declare attribute with embedded keyword

Try it

Use executable documentation to see it in action.

Billy

itSync "should be fine with Mary", ->
  Patient.create
    name        : 'Billy'
    temperature : 36

  billy = Patient.first()
  billy.temperature.should be: 36
  

-->

Thanks for watching


Mongo Model

https://github.com/al6x/mongo-model
Documentation
Examples

Me

Alexey Petrushin
alexey.petrushin at gmail

Your browser doesn't support the features required by impress.js, so you are presented with a simplified version of this presentation.

For the best experience please use the latest Chrome or Safari browser. Firefox 10 (to be released soon) will also handle it.

Use a spacebar or arrow keys to navigate