0

I want to set the data type of _id field of my model to Number instead of ObjectId and mongodb should auto generate _id as serial numbers when new document is saved.

I tried setting _id to Number as shown below but it does not work and _id value is generated ObjectId.

const mySchema = new Schema({
  _id: Number
});
  • See https://stackoverflow.com/questions/15508912/mongoose-auto-increment – Lin Du Jun 14 '23 at 12:00
  • Does this answer your question? [Mongoose auto-increment](https://stackoverflow.com/questions/15508912/mongoose-auto-increment) – umitu Jun 14 '23 at 12:45
  • Mongoose-auto-increment is no longer available and it's github page is also gone. Another library mongoose-sequence is also no longer maintained as mentioned in the readme. – Ankur Kumar Jun 16 '23 at 08:18

1 Answers1

0
const mongoose = require('mongoose');

// Custom schema type for positive integers
function NumberId(key, options) {
  // Call parent constructor with custom name
  mongoose.SchemaType.call(this, key, options, 'NumberId');
}

// Inherit from SchemaType
NumberId.prototype = Object.create(mongoose.SchemaType.prototype);

// Implement the `cast()` method
NumberId.prototype.cast = function (val) {
  if (typeof val !== 'number') {
    throw new Error('NumberId: ' + val + ' is not a number');
  }
  if (val % 1 !== 0) {
    throw new Error('NumberId: ' + val + ' is not an integer');
  }
  if (val < 0) {
    throw new Error('NumberId: ' + val + ' is negative');
  }
  return val;
};

// Register the new schema type
mongoose.Schema.Types.NumberId = NumberId;

// Create a new schema using our schema type
const schema = new mongoose.Schema(
  {
    _id: { type: mongoose.Schema.Types.NumberId, required: true, unique: true },
    // Other fields in your schema
  },
  { autoIndex: false }
);

// Create a model using our schema
const Model = mongoose.model('Model', schema);

const mongoUri = 'mongodb://localhost:27017/test';

async function run() {
  // Connect to MongoDB
  await mongoose.connect(mongoUri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });

  // Create some documents
  await Model.create({ _id: 1 });
  await Model.create({ _id: 2 });
  await Model.create({ _id: 3 });
}

run();
Md Azad
  • 1
  • 1