This error occurs when you attempt to save a document with fields that are not defined in your Mongoose schema while strict mode is set to "throw". The fix involves either adding missing fields to your schema or adjusting your strict mode configuration.
Fixes StrictModeError: Field is not in schema and strict mode is set to throw
const userSchema = new mongoose.Schema({
name: String,
email: String,
phone: String // Add the missing field
});const userSchema = new mongoose.Schema({name: String,email: String,phone: String // Add the missing field});StrictModeError: Field is not in schema and strict mode is set to throw
Mongoose strict mode is a schema validation setting that controls how the library handles properties not explicitly defined in your schema. When set to "throw", it will raise a StrictModeError instead of silently ignoring undefined fields. This error commonly appears when you try to set properties on a model instance, update documents with unexpected fields, or work with retrieved documents that include virtual fields. The error acts as a safeguard to prevent accidental data inconsistencies and ensure your database documents match your schema definition.
Review the error message to identify which field is not in the schema. Add it to your schema definition with the appropriate type:
const userSchema = new mongoose.Schema({
name: String,
email: String,
phone: String // Add the missing field
});If the error occurs when saving a retrieved document, check if you are including virtual fields. Remove them before saving or configure your schema to exclude them:
const userSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
// Add a virtual field
userSchema.virtual("fullName").get(function() {
return `${this.firstName} ${this.lastName}`;
});
// When retrieving, exclude virtuals
const user = await User.findById(id).lean();
// Or convert to plain object and remove virtuals before saving
const plainUser = user.toObject({ virtuals: false });
await user.save();If you intentionally want to allow extra fields or are working with dynamic schemas, disable strict mode:
const userSchema = new mongoose.Schema(
{
name: String,
email: String
},
{ strict: false } // Allow undefined fields
);Note: This is generally not recommended for production as it can lead to inconsistent documents.
If you only need to allow extra fields for certain operations, set strict mode locally:
// Allow extra fields in this update
await User.updateOne(
{ _id: userId },
{ $set: updateData },
{ strict: false }
);
// Or when creating a document
const user = new User({ name: "John", ...extraFields });
await user.save({ validateBeforeSave: true }); // strict still applies
// For bulk operations
await User.collection.insertMany(documentsWithExtraFields, { ordered: false });If using nested schemas, ensure they have compatible strict settings. Use useNestedStrict option if child schemas have different settings:
const childSchema = new mongoose.Schema({
value: String
}, { strict: false });
const parentSchema = new mongoose.Schema({
child: childSchema
}, {
strict: "throw",
useNestedStrict: true // Use child schema strict setting
});For external data (API responses, imports), explicitly filter to only include schema-defined fields:
const userSchema = new mongoose.Schema({
name: String,
email: String
});
const schemaFields = Object.keys(userSchema.paths);
const externalData = { name: "John", email: "[email protected]", extra: "field" };
// Filter to only schema fields
const filteredData = Object.fromEntries(
Object.entries(externalData).filter(([key]) => schemaFields.includes(key))
);
const user = new User(filteredData);
await user.save();Strict mode defaults to true in Mongoose and is a security feature to prevent unintended schema pollution. When set to "throw" (instead of just true), it actively raises errors rather than silently dropping fields, making it easier to catch schema mismatches during development. MongoDB itself does not enforce strict schema validation by default—this is a Mongoose-level protection. If you need to work with dynamic fields, consider using a separate JSON/Object field in your schema rather than disabling strict mode entirely. For large-scale data migrations from non-Mongoose sources, you may want to temporarily set strict: false during the import process, then enable it again for normal operations. The strictQuery option is separate and controls query filter validation—these can be configured independently.