an auto-increment version in document creation mongoose

Viewed 639

I want that when a new document is created the versionKey (__v) field will auto-increment.

(or should I use a new field 'version' instead __v in the schema?)

example for the schema in my app :

Template.js

var mongoose = require('mongoose');
const Test = require('./Test');

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

TemplateSchema.pre('save', function(next) {
  this.increment();
  return next();
});

module.exports = mongoose.model('Template', TemplateSchema);

routes/templatesApi.js

// create new template document
router.post('/', function(req, res, next) {
    Test.create(req.body, function (err, tests) {
        if (err) {
            console.log(err);
            return next(err);
        }
        res.json(tests);
    });
});

where and how can I insert the auto-increment operation for versionKey property here?

Edit: I tried to use .pre('save') middleware and it still not working.

am I using it right?

1 Answers

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
Related