You need to enable JavaScript to run this app. Mongoose Schema中如何生成1、2、3之类的连续自增序列号
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose Schema中如何生成1、2、3之类的连续自增序列号

Mongoose 生成自增序列号实现方案

以下两种方案都可以实现插入数据时自动生成1、2、3依次递增的序列号,可根据项目场景选择。

方案1:独立计数器集合实现(推荐生产环境使用)

该方案利用MongoDB单文档操作的原子性,通过专门的计数器集合维护序列号的递增状态,不会出现并发重复问题,也不会因为业务数据删除导致序列号重置。

  1. 首先定义计数器集合的Schema和模型
const mongoose = require('mongoose');

const counterSchema = new mongoose.Schema({
  // 对应要生成自增序列的业务集合名称
  collectionName: {
    type: String,
    required: true,
    unique: true
  },
  // 当前已使用的最大序列号
  currentSeq: {
    type: Number,
    default: 0
  }
});

const Counter = mongoose.model('Counter', counterSchema);
  1. 定义你的业务集合Schema,添加序列号字段
// 示例为订单业务集合,可替换为你自己的业务模型
const orderSchema = new mongoose.Schema({
  // 你的其他业务字段,比如订单名称、金额等
  orderName: String,
  amount: Number,
  // 自增序列号字段
  seq: {
    type: Number,
    unique: true,
    required: true
  }
});
  1. 给业务Schema添加保存前的钩子,自动生成序列号
orderSchema.pre('save', async function(next) {
  // 仅当是新文档插入时生成序列号
  if (this.isNew) {
    const counter = await Counter.findOneAndUpdate(
      { collectionName: 'orders' }, // 和业务集合名对应
      { $inc: { currentSeq: 1 } }, // 原子操作:序列号+1
      { new: true, upsert: true } // 不存在计数器记录时自动创建,返回更新后的值
    );
    this.seq = counter.currentSeq;
  }
  next();
});

const Order = mongoose.model('Order', orderSchema);

方案2:查询业务集合最大值实现(适合低并发小型项目)

该方案无需额外创建集合,实现简单,但高并发场景下可能出现重复序列号,且业务数据清空后序列号会从1重新开始。

const orderSchema = new mongoose.Schema({
  // 其他业务字段
  orderName: String,
  amount: Number,
  seq: {
    type: Number,
    unique: true,
    required: true
  }
});

orderSchema.pre('save', async function(next) {
  if (this.isNew) {
    // 查询当前集合中最大的序列号
    const maxSeqDoc = await Order.findOne().sort({ seq: -1 }).select('seq');
    // 如果没有数据则从1开始,否则最大值+1
    this.seq = maxSeqDoc ? maxSeqDoc.seq + 1 : 1;
  }
  next();
});

const Order = mongoose.model('Order', orderSchema);

Express 接口调用示例

无需在接口中手动处理序列号,直接正常调用保存方法即可:

const express = require('express');
const app = express();
app.use(express.json());

app.post('/api/orders', async (req, res) => {
  try {
    const newOrder = new Order(req.body);
    await newOrder.save();
    res.status(201).json(newOrder);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

app.listen(3000, () => console.log('服务启动在3000端口'));

注意事项

  • 生产环境高并发场景优先选择方案1,避免序列号重复
  • 序列号字段建议添加unique: true唯一索引,异常情况下重复插入会抛出错误可进行重试处理
  • 批量插入数据时pre('save')钩子不会触发,需要单独批量生成序列号后再插入

内容的提问来源于stack exchange,提问作者Shanthi B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 16:27:04