forked from Snkz/mongoose-rollback
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoose-rollback.js
53 lines (41 loc) · 1.47 KB
/
mongoose-rollback.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
var RollbackSchema = require('./models/rollback.js');
var buildRollbackMethods = require('./lib/methods.js');
var buildSaveMethods = require('./lib/save.js');
var buildStaticFunctions = require('./lib/statics.js');
var models = {};
function rollbackPlugin (schema, options) {
/* SCHEMA CHANGES */
var collectionName = options.collectionName + "_hist";
var Rollback;
schema.add({ _version: {
type: Number,
default: 0
}
})
// assumes connection happens before plugin or something? not sure but yea..
var mongoose = require('mongoose');
var conn = mongoose;
// add index on version field
if (options && options.index) {
schema.path('_version').index(options.index)
}
// get connection
if (options && options.conn) {
var conn = mongoose.connect(options.conn);
}
// avoid recompilation
if (models[collectionName]) {
Rollback = models[collectionName];
} else {
models[collectionName] = conn.model(collectionName, RollbackSchema, collectionName);
Rollback = models[collectionName];
}
schema.statics.RollbackModel = Rollback;
/* STORAGE METHODS (happen transparently) */
buildSaveMethods(schema, options);
/* DOCUMENT METHODS (happen on instances of a model)*/
buildRollbackMethods(schema, options);
/* SCHEMA FUNCTIONS (statics altering collection */
buildStaticFunctions(schema, options);
}
module.exports = rollbackPlugin;