Created
August 19, 2012 09:21
-
-
Save hfcorriez/3393918 to your computer and use it in GitHub Desktop.
Simple Pub/Sub model with NodeJs+Mongoose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
var db = mongoose.createConnection('127.0.0.1', 'test'); | |
// Make schema | |
var schema = mongoose.Schema({ name: String }); | |
// Create subscribers collection | |
var subscribers = []; | |
// Hook `save` post method | |
schema.post('save', function () { | |
console.log(this.name); | |
for (var i in subscribers) { | |
subscribers[i](this); | |
} | |
return true; | |
}); | |
// Add static method for schema | |
schema.static('subscribe', function (subscriber) { | |
subscribers.push(subscriber); | |
}); | |
// Create model from schema | |
var Cat = db.model('Cat', schema); | |
// Subscriber data changes | |
Cat.subscribe(function (data) { | |
console.log('receive data:'); | |
console.log(data); | |
}); | |
// Create new cat with name kitty. | |
new Cat({ name: 'kitty' }).save(function (err) { | |
console.log(err); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is not working If I inserted data from mongo console