Skip to content

Instantly share code, notes, and snippets.

@gjohnson
Created December 20, 2012 22:33
Show Gist options
  • Save gjohnson/4349157 to your computer and use it in GitHub Desktop.
Save gjohnson/4349157 to your computer and use it in GitHub Desktop.
mongoose revision plugin
var mongoose = require('mongoose')
, revision = require('..')
, Schema = mongoose.Schema;
mongoose.connect('localhost', 'sandbox');
var schema = new Schema({
title: String,
content: String
});
schema.plugin(revision);
var Post = mongoose.model('Post', schema);
Post.findOne({ title: 'js 101' }, function(err, post){
if (err) return done(err);
if (!post) post = new Post({ title: 'js 101' });
next(post);
});
function next(post){
post.content = String(Date.now());
post.save(done);
}
function done(err, post){
if (err) throw err
else console.log('post: %j', post);
}
function revision(schema, options){
schema.add({ revision: { type: Number, default: 1 }});
schema.pre('save', function(next){
if (!this.isModified()) return next();
var self = this
, db = this.db
, shadow = this.toObject()
, name = this.constructor.collection.collection.collectionName
, collection = db.collection(name + '_revisions');
shadow._id = {
_id: this.id,
revision: this.revision
};
collection.insert(shadow, function(err){
if (err) return next(err);
self.revision += 1;
next();
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment