Created
December 20, 2012 22:33
-
-
Save gjohnson/4349157 to your computer and use it in GitHub Desktop.
mongoose revision plugin
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') | |
, 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); | |
} |
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
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