Node.js 在MongoDB架构中自动递增前导为0的字段

Node.js 在MongoDB架构中自动递增前导为0的字段,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我正在为发票实现MongoDB模式 我想知道如何在insert上增加id字段 问题是我需要id以具有前导0 例如,系统中的第一张发票应具有以下ID: 0000001 我需要这样才能向用户显示发票序列号 var InvoiceSchema = new Schema({ /* invoiceId: { type: Number }, */ created: { type: Date, default: Date.now, }, status: {

我正在为发票实现MongoDB模式

我想知道如何在insert上增加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
  }
});

据我所知,mongo不支持自动增量。但你可以做一些小把戏。
当您插入项目时,您可以使用Fцndadmodify查询并将新id存储在其他集合中。示例是

,因为我知道mongo不支持自动增量。但你可以做一些小把戏。
当您插入项目时,您可以使用Fцndadmodify查询并将新id存储在其他集合中。例如,

有一个插件我没有使用过,它可以处理自动增量

如果您想自己为这种特定情况编写代码,您可以遵循这一点,这似乎非常简单

应该是这样的:

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,我建议使用virtuals。假设您需要7位数字:

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

有一个插件我没有使用过,它可以处理自动递增

如果您想自己为这种特定情况编写代码,您可以遵循这一点,这似乎非常简单

应该是这样的:

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,我建议使用virtuals。假设您需要7位数字:

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

你在使用猫鼬吗?有没有解决你的问题的答案?还是还没有解决?@EnriqueFueyo仍然没有解决-等待更多答案ideas@martynas如果你描述一下为什么Enrique的答案对你不起作用,那会有帮助。你是在用猫鼬吗?有没有解决你的问题的答案?还是仍然没有解决?EnriqueFueyo仍然没有解决-等待更多ideas@martynas如果你能描述一下为什么恩里克的答案对你不起作用,这会有所帮助。