Skip to content

Instantly share code, notes, and snippets.

@capaj
Last active December 27, 2015 13:29
Show Gist options
  • Save capaj/7333578 to your computer and use it in GitHub Desktop.
Save capaj/7333578 to your computer and use it in GitHub Desktop.
a little exercise showing how to use mongoose middleware
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title: String,
author: String,
body: String,
date: { type: Date, default: Date.now }
});
var blogModel = mongoose.model('Blog', blogSchema);
mongoose.connect("mongodb://localhost/mwtest", function (err) {
// if we failed to connect, abort
if (err) {
throw err;
} else {
console.log("DB connected succesfully");
}
blogSchema.pre('save', function preSave(next) {
this._wasNew = this.isNew;
console.log("pre save of doc: " + this._id);
next();
});
blogSchema.post('save', function (doc) {
if (doc._wasNew) {
console.log("created new doc: " + doc._id);
} else {
console.log("updated doc: " + doc._id);
}
return true;
});
blogSchema.post('remove', function (doc) {
console.log("post remove of doc: " + doc._id);
});
blogSchema.pre('remove', function (next) {
console.log("pre remove of doc: " + this._id);
next();
});
blogModel.create({title: 'Philip is good', author: 'George'}).then(function (doc) {
console.log("create callback doc: " + JSON.stringify(doc));
blogModel.findById(doc._id, function (err, doc) {
doc.remove();
console.log("after removal of doc: " + doc._id);
});
});
});
@capaj
Copy link
Author

capaj commented Nov 6, 2013

And the output is:
DB connected succesfully
pre save of doc: 527a14f93cf78b8e04000001
created new doc: 527a14f93cf78b8e04000001
create callback doc: {"__v":0,"title":"Philip is good","author":"George","_id":"527a14f93cf78b8e04000001","date":"2013-11-06T10:07:53.327Z"}
pre remove of doc: 527a14f93cf78b8e04000001
after removal of doc: 527a14f93cf78b8e04000001
post remove of doc: 527a14f93cf78b8e04000001

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment