Skip to content

Latest commit

 

History

History
68 lines (49 loc) · 1.91 KB

examples.md

File metadata and controls

68 lines (49 loc) · 1.91 KB

Examples

Increments version on updates

const schema = new mongoose.Schema({
  name: String,
  colors: [{ name: String }]
});

// Add this plugin
schema.plugin(updateVersioningPlugin);

const Model = mongoose.model('Toy', schema);

// Create a doc that we'll update later. Starts with version 0...
let doc = yield Model.create({
  name: 'Turbo Man',
  colors: [{ name: 'red' }]
});
assert.equal(doc.__v, 0);

// This plugin will increment the document version
doc = yield Model.findOneAndUpdate(
  {},
  { $push: { colors: { name: 'gold' } } },
  { new: true }
);
assert.equal(doc.__v, 1);

Only increments when updating an array

Mongoose versioning only triggers a version bump when you modify an array. That's because the primary purpose of versioning is to protect you from, for example, overwriting the 3rd element in an array when someone deleted the 3rd element underneath you. Updating just the name will not trigger a version bump.

let doc = yield Model.findOneAndUpdate({}, { name: 'Santa' }, { new: true });
assert.equal(doc.__v, 0); // Did **not** bump the version

Strips out version key overwrites

The update versioning plugin will strip out any existing modifications to the version key. If you want to explicitly overwrite the version key, you should pass version: false to your Mongoose query options.

let doc = yield Model.findOneAndUpdate({}, { __v: 1225 }, { new: true });
// The update versioning plugin prevented overwriting `__v`
assert.equal(doc.__v, 0);

doc = yield Model.findOneAndUpdate({}, { __v: 1225 }, {
  new: true,
  version: false // Skip update versioning for this one update
});
// Overwrote the version key
assert.equal(doc.__v, 1225);