Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose auto-increment

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.

like image 405
user1257255 Avatar asked Mar 19 '13 19:03

user1257255


People also ask

What is mongoose-auto-increment?

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?

Is mongoose-auto-increment popular on Snyk advisor?

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?

How many times has mongoose-auto-increment been starred?

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.

How do I increase a number in mongoose?

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.


1 Answers

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();
     });
like image 106
Anees Hameed Avatar answered Sep 18 '22 00:09

Anees Hameed