SchemaType.prototype.immutable()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Defines this path as immutable. Mongoose prevents you from changing immutable paths unless the parent document has isNew: true.

Example:

  1. const schema = new Schema({
  2. name: { type: String, immutable: true },
  3. age: Number
  4. });
  5. const Model = mongoose.model('Test', schema);
  6. await Model.create({ name: 'test' });
  7. const doc = await Model.findOne();
  8. doc.isNew; // false
  9. doc.name = 'new name';
  10. doc.name; // 'test', because `name` is immutable

Mongoose also prevents changing immutable properties using updateOne() and updateMany() based on strict mode.

Example:

  1. // Mongoose will strip out the `name` update, because `name` is immutable
  2. Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } });
  3. // If `strict` is set to 'throw', Mongoose will throw an error if you
  4. // update `name`
  5. const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }).
  6. then(() => null, err => err);
  7. err.name; // StrictModeError
  8. // If `strict` is `false`, Mongoose allows updating `name` even though
  9. // the property is immutable.
  10. Model.updateOne({}, { name: 'test2' }, { strict: false });