I would like to create auto increment ID with Mongoose for MongoDB. I was already looking for some examples, but there aren't anything useful other the MongoDB's documentation.
This plugin allows you to auto-increment any field on any mongoose schema that you wish. Visit Snyk Advisor to see a full health score report for mongoose-auto-increment, including popularity, security, maintenance & community analysis. Is mongoose-auto-increment popular?
The npm package mongoose-auto-increment receives a total of 8,059 weekly downloads. As such, mongoose-auto-increment popularity was classified as small. Visit the popularity section on Snyk Advisor to see the full health analysis. Is mongoose-auto-increment well maintained?
Based on project statistics from the GitHub repository for the npm package mongoose-auto-increment, we found that it has been starred 329 times, and that 83 other projects in the ecosystem are dependent on it. Downloads are calculated as moving averages for a period of the last 12 months, excluding weekends and known missing data points.
mongoose-auto-increment. Mongoose plugin that auto-increments any ID field on your schema every time a document is saved. This is the module used by mongoose-simpledb to increment Number IDs. You are perfectly able to use this module by itself if you would like.
Use mongoose-sequence, For eg: In the below model, it increments order number by one when a new document is inserted.
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const AutoIncrement = require('mongoose-sequence')(mongoose);
const orderSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,
orderId: {
type: Number
}
...
});
orderSchema.plugin(AutoIncrement, {inc_field: 'orderId'});
module.exports = mongoose.model('Order', orderSchema);
There is an important thing that needs to be understood. If you add required: true in the schema, the operation breaks.
In your route file, you can create a mongoose order object and call save.
...
const order = new Order(body);
order.save()
.then(doc => {
res.json(doc);
res.end();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With