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

相关文章:

  • 2022-01-30
  • 2022-02-16
  • 2022-12-23
  • 2022-02-01
  • 2021-08-18
猜你喜欢
  • 2022-12-23
  • 2021-12-08
  • 2021-07-25
  • 2021-06-23
  • 2022-12-23
  • 2021-05-23
  • 2022-02-01
相关资源
相似解决方案