mongoose 创建自增字段方法

first: create counter collection in mongodb:
> db.counters.insert({_id:"entityId",seq:0})
WriteResult({ "nInserted" : 1 })


then put below in a model.js:

var CounterSchema = Schema({
_id: {type: String, required: true},
seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);

 

var entitySchema = mongoose.Schema({
testvalue: {type: String}
});

entitySchema.pre('save', function(next) {
var doc = this;
counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1} }, function(error, counter) {
if(error)
return next(error);
doc.testvalue = counter.seq;
next();
});
});

 

 

借鉴: http://stackoverflow.com/questions/28357965/mongoose-auto-increment

I'm falling off the sky all alone.The courage inside is gonna break the fall. Nothing can dim my light within. I am That I am 程序 = 数据结构 + 算法
posted @ 2016-07-13 22:19  IamThat  阅读(8188)  评论(0编辑  收藏  举报