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:
const schema = new Schema({
name: { type: String, immutable: true },
age: Number
});
const Model = mongoose.model('Test', schema);
await Model.create({ name: 'test' });
const doc = await Model.findOne();
doc.isNew; // false
doc.name = 'new name';
doc.name; // 'test', because `name` is immutable
Mongoose also prevents changing immutable properties using updateOne()
and updateMany()
based on strict mode.
Example:
// Mongoose will strip out the `name` update, because `name` is immutable
Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } });
// If `strict` is set to 'throw', Mongoose will throw an error if you
// update `name`
const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }).
then(() => null, err => err);
err.name; // StrictModeError
// If `strict` is `false`, Mongoose allows updating `name` even though
// the property is immutable.
Model.updateOne({}, { name: 'test2' }, { strict: false });
当前内容版权归 mongoosejs 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 mongoosejs .