简体   繁体   English

如何创建在MongoDB中插入新记录后将自动递增的字段?

[英]How to create field that will auto increment after insertion of new record in MongoDB?

I'm using Mongoose and Node.js 我正在使用Mongoose和Node.js

The Schema of the model is as follows: 该模型的架构如下:

let orderSchema = new Schema({
    'product': String,
    'orderNumber': Number,
    'totalPrice': Number,
    'customer': {
        'type': Schema.Types.ObjectId,
        'ref': 'Users'
    });

I want to set the orderNumber as an increamenting integer. 我想将orderNumber设置为无整数。

Is there any way to do it in MongoDB? MongoDB中有什么办法吗?

I don't want to use the pre-hook technique to do it 我不想使用预钩技术

You need to create a collection with counters and a plugin with two hooks inside: 您需要创建一个带有计数器的集合以及一个内部带有两个钩子的插件

  1. schema.pre - to get the current value of counter schema.pre获取计数器的当前值
  2. schema.post - to save new value of counter schema.post保存计数器的新值

Counter schema will look like this: 计数器架构如下所示:

const conterSchema = new Schema({
  name: String,
  value: Number
});

While the plugin will can be defined like this: 虽然插件可以这样定义:

function incrementOrderNumber (schema) {
  schema.pre('save', next => {
    CounterModel.findOne({ name: 'orderNumberCounter' })
      .then(counterDoc => counterDoc.toObject())
      .then(({ value}) => {
        this.orderNumber = value;
        next();
      });
  });

  schema.post('save', next => {
    CounterModel.findOneAndUpdate({ name: 'orderNumberCounter' }, { $inc: { value: 1 }}).exec();
  });
}

After creating such plugin function you will need to plug it into your schema: 创建了此类插件功能后,您需要将其插入架构中:

orderSchema.plugin(incrementOrderNumber);

Do not forget to insert orderNumberCounter into counters collection. 不要忘记将orderNumberCounter插入counters集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM