-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
41 lines (33 loc) · 980 Bytes
/
index.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
var mongoose = require('mongoose');
var counterSchema = mongoose.Schema({
Name:{
type: String,
trim: true,
required: true
},
Sequence:{
type: Number,
required: false
}
});
function init(schema,options){
if(!options || !options.column){
if(!schema.hasOwnProperty('_id'))
schema.add({_id:{type: Number,unique:true}});
}
}
var Counter = mongoose.model('Counter',counterSchema);
module.exports = function autoIncrementPlugin(schema, options){
init(schema,options);
schema.pre('save', function(next){
var doc = this;
Counter.findOneAndUpdate({Name: doc.constructor.collection.name}, {$inc:{Sequence:1}, Name: doc.constructor.collection.name}, {upsert: true}, function(err, counter){
if(err)
return next(err);
if(!options || !options.column)
options = {column: '_id'};
doc[options.column] = (!counter || !counter.Sequence)? 0:counter.Sequence;
next();
});
});
}