MongoDB中如何设置自增ID字段?

更新于
2026-09-30 18:30:28
1阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计91个文字,预计阅读时间需要1分钟。

MongoDB中如何设置自增ID字段?

javascriptconst mongoose=require('mongoose');const Schema=mongoose.Schema;

let counter=1;const CountedId={ type: Number, default: ()=> counter++ };

const ModelSchema=new Schema({ id: CountedId });

MongoDB中如何设置自增ID字段?

const Model=mongoose.model('Mod');

Model.js

const Mongoose = require('mongoose'); const Schema = Mongoose.Schema; let counter = 1; let CountedId = {type: Number, default: () => counter++}; const ModelSchema = new Schema({ id: CountedId, // .... }); const Model = Mongoose.model('Model', ModelSchema); module.exports = Model; Model.find({ id: { $gt: 0 } }).sort({ id: -1 }) .then(([first, ...others]) => { if (first) counter = first.id + 1; });

本文共计91个文字,预计阅读时间需要1分钟。

MongoDB中如何设置自增ID字段?

javascriptconst mongoose=require('mongoose');const Schema=mongoose.Schema;

let counter=1;const CountedId={ type: Number, default: ()=> counter++ };

const ModelSchema=new Schema({ id: CountedId });

MongoDB中如何设置自增ID字段?

const Model=mongoose.model('Mod');

Model.js

const Mongoose = require('mongoose'); const Schema = Mongoose.Schema; let counter = 1; let CountedId = {type: Number, default: () => counter++}; const ModelSchema = new Schema({ id: CountedId, // .... }); const Model = Mongoose.model('Model', ModelSchema); module.exports = Model; Model.find({ id: { $gt: 0 } }).sort({ id: -1 }) .then(([first, ...others]) => { if (first) counter = first.id + 1; });