Skip to content

Commit

Permalink
Improve README for better clarity.
Browse files Browse the repository at this point in the history
  • Loading branch information
fzaninotto committed Jun 13, 2012
1 parent 40d8f6b commit 51f4d63
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
42 changes: 40 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mongoose-lifecycle
==================

Mongoose plugin adding lifecyle events on the model class.
[Mongoose](https://github.com/LearnBoost/mongoose) plugin adding lifecyle events to the model class.

Installation
------------
Expand Down Expand Up @@ -30,6 +30,7 @@ Initialization is straightforward:
```javascript
var Book = new Schema({ ... });
Book.plugin(require('mongoose-lifecycle'));
module.exports = mongoose.model('Book', Book);
```

Now the model emits lifecycle events before and after persistence operations:
Expand All @@ -48,10 +49,47 @@ You can listen to these events directly on the model.
```javascript
var Book = require('path/to/models/book');
Book.on('beforeInsert', function(book) {
// do stuff...
console.log('A new book "%s" was inserted', book.title);
});
```

The `beforeInsert` event is emitted just before a new document is persisted:

```javascript
var book = new Book();
book.title = 'War and Peace';
book.save(); // logs the book title to the console
});
```

Why Not Use The `save` and `remove` events?
-------------------------------------------

Because you may not have access to the right class to register them.

```javascript
// if you register an event listener on the Schema class, it works
// in models/book.js
var Book = new Schema({ ... });
Book.pre('save', function(next) {
console.log('A new book "%s" was inserted', this.title);
next();
});

// if you register an event listener on the Model class, it doesn't work
// in models/book.js
var Book = new Schema({ ... });
module.exports = mongoose.model('Book', Book);
// in a controller class
var Book = require('path/to/models/book'); // Book is a Model, not a Schema
Book.pre('save', function(next) {
console.log('A new book "%s" was inserted', this.title);
next();
});
```

The plugin does the work of finding the Schema back from the Model class. It also allows you to use the standard `on()` method to register event listeners, instead of the custom `pre()` and `post()` Mongoose methods. Lastly, it makes a difference between insert and update persistence operations, while Mongoose only provides a `save` event.

License
-------

Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
},
"devDependencies": {
"should": ">=0.2.1",
"mongoose": ">=2.6.5",
"cli-table" : ">=0.0.1"
"mongoose": ">=2.6.5"
},
"license": "MIT",
"engine": {
Expand Down

0 comments on commit 51f4d63

Please sign in to comment.