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();