Mongoose Auto Increment

Mongoose auto increment

Here is an example how you can implement auto-increment field in Mongoose:

var CounterSchema = Schema({
_id: {type: String, required: true},
seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);

var entitySchema = mongoose.Schema({
testvalue: {type: String}
});

entitySchema.pre('save', function(next) {
var doc = this;
counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1} }, function(error, counter) {
if(error)
return next(error);
doc.testvalue = counter.seq;
next();
});
});

an auto-increment version in document creation mongoose

Customize __v key name

Yes we can change __v default key name to any custom versionKey

var TemplateSchema = new mongoose.Schema(
{
platform: String,
templateRevision: String,
tests: [Test.schema]
},
{ versionKey: 'version' }
);

Auto increment version

below middleware will call before operation and update incremented version,

  • Increment when save(), this refers to document object
TemplateSchema.pre('save', function(next) {
this.increment();
return next();
});
  • increment when updateMany(), this refers to query object
TemplateSchema.pre('updateMany', function(next) {
this.updateMany({}, { $inc: { version: 1 } });
return next()
});

Same way you can create middleware for other methods update(), updateOne(), findOneAndUpdate(), findAndModify() and etc.

  • we are working in Template.js file and last you need to create a model for schema and export, that you have already did.
module.exports = mongoose.model('Template', TemplateSchema);

Examples

  • load models
const Template = require('./Template'); // manage path of Template.js
  • find one and save
let doc = Template.findOne({ _id: "5f299bdbf045394388fc1461" });
doc.platform = "test platform";
doc.save(); // before this, `save` middleware will call and auto increment version by 1
  • update multiple documents
Template.updateMany(
{ platform: "test platform" },
{ $set: { platform: "demo platform" } }
);
// before this, `updateMany` middleware will call and increment version by 1

how can I create a auto-increment field in mongoose

there is a very simple and easy way to implement auto increment in mongoose by using mongoose pre save function. Here are my codes for user collection, try the same trick in your mongoose model(schema) to implement auto increment. Paste this code in your collection schema file and replace some variables(userSchema, user) according to your collection schema.

userSchema.pre('save', function(next) {
var currentDate = new Date();
this.updated_at = currentDate;

if (!this.created_at)
this.created_at = currentDate;

var sno = 1;
var user = this;
User.find({}, function(err, users) {
if (err) throw err;
sno = users.length + 1;
user.sno = sno;
next();
});
});


Related Topics



Leave a reply



Submit