使用MongoDB模式中的前导0自动递增字段

我正在实现发票的MongoDB模式。

我想知道如何增加插入的id字段?

赶上是我需要ID领先0。

例如,系统中的第一张发票应具有以下ID:

0000001

我需要这个能够显示发票序列号给用户。

 var InvoiceSchema = new Schema({ /* invoiceId: { type: Number }, */ created: { type: Date, default: Date.now, }, status: { type: String, enum: ['Paid', 'Unpaid'] }, net: { type: Number }, vat: { type: Number }, total: { type: Number }, products: [{ product: { type: String, default: '', trim: true }, description: { type: String, default: '', trim: true }, quantity: { type: Number }, unitCost: { type: Number }, vat: { type: Number }, total: { type: Number } }], billingDetails: [BillingDetails], user: { type: Schema.ObjectId, ref: 'User', required: true } }); 

有一个插件(我没有使用)叫做mongoose-auto-increment ,它将处理自动增量。

如果你想自己编写这个特定的情况,你可以按照这个MongoDb教程 ,这似乎是非常简单的。

它应该是这样的:

 var InvoiceSchema = new Schema({..}) InvoiceSchema.pre('save', function (done) { if (this.isNew){ //new Record => create //this function is the one that should do the FindAndModify stuff getNewId(function(autoincremented_id){ this.id=autoincremented_id; done() }) }else{ done() } }); 

对于领先的0,我会build议使用虚拟。 假设你想要7位数字:

 InvoiceSchema.virtual('formattedId').get(function () { return ("0000000"+this.id).slice(-7); }); InvoiceSchema.virtual('formattedId').set(function (arg_id) { this.id = parseInt(arg_id); }); 

据我所知,mongo不支持自动增量。 但你可以做小动作。 当你插入项目你使用F ndndAndModify查询和存储新的ID在其他集合。 例子在mongodb博客上发布