最近幫朋友弄一個小項目,數據庫最初選定了mongodb,后來在需求文檔中發現對玩家的id有自增的需求。這放在mysql中是天生支持的,可是在mongodb中為了分布式部署不出現id沖突,id是由機器名、時間等共同組成的。所以這個需求我們假設是mongodb單機部署,將來也不會分片的前提下才能按照本文的方法去做。
大致的思想是創建一個公共的counter集合,它記錄其他集合的id數值,其他集合需要自增id前,先原子增加counter中對應的字段,然后用返回的增加后的值賦予自增id。用mongoose實現的話,可以hook住save之前的操作,讓自增透明化,關鍵代碼如下:
const CounterSchema = dbHelper.mongoose.Schema({ _id: { type: String, required: true }, seq: { type: Number, default: 0 } }); const Counter = dbHelper.mongoose.model('counter', CounterSchema); playerSchema.pre('save', function (next) { let doc = this; Counter.findByIdAndUpdate({ _id: 'playerId' }, { $inc: { seq: 1 } }, { new: true, upsert: true }, function (error, counter) { if (error) return next(error); doc.id = counter.seq; next(); }); });