码迷,mamicode.com
首页 > 其他好文 > 详细

mongoose 创建自增字段方法

时间:2016-07-14 02:18:37      阅读:1411      评论:0      收藏:0      [点我收藏+]

标签:

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

mongoose 创建自增字段方法

标签:

原文地址:http://www.cnblogs.com/IamThat/p/5668411.html

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!