When working with Mongoose to interact with your document database, you might encounter a DeprecationWarning: Mongoose: the strictQuery
option will be switched back to false
by default in Mongoose 7.
The system shows the DeprecationWarning: Mongoose: the strictQuery option will be switched back to false
by default in Mongoose 7 message because your Mongoose library currently uses the strictQuery=true
mode. In future, you might upgrade to Mongoose version 7.0, and the default behaviour of the strictQuery
will be changed to strictQuery=false
in Mongoose version 7.0, and you need to make a note of this change.
This tutorial teaches you what StrictQuery
is, what the true
or false
property of StrictQuery
does, and when to use these modes.
What is StrictQuery
The strictQuery
sets the strict mode for the query filters.
It defines how to handle the fields that are NOT defined in the schema while filtering the records.
- If the strictQuery is set to
true
, only the fields defined in the schema will be cast during the query casting - If the strictQuery is set to
false
, all the fields(Including the undefined fields) will be cast during the query casting
When to Use strictQuery=true Mode
Use the strictQuery=true
mode when you want to cast only the fields defined in your schema.
In the following example, Mongoose will strip out notInSchema: 1
because strictQuery
is true
by default though it is not explicitly mentioned.
const mySchema = new Schema({ field: Number }, { strict: true });
const MyModel = mongoose.model('Test', mySchema);
MyModel.find({ notInSchema: 1 });
When to Use strictQuery=false Mode
Use the strictQuery=true
mode when you want to cast only the fields defined in your schema. For example,
In the following example, Mongoose will not strip out notInSchema: 1
because strictQuery
is false
.
const mySchema = new Schema({ field: Number }, {
strict: true,
strictQuery: false // Turn off strict mode for query filters
});
const MyModel = mongoose.model('Test', mySchema);
MyModel.find({ notInSchema: 1 });
How to Avoid the DeprecationWarning: Mongoose: the strictQuery option will be switched back to false by default in Mongoose 7 warning
You can avoid/hide the DeprecationWarning: Mongoose: the strictQuery option will be switched back to false
by default in Mongoose 7 warning and prepare for the new release later by setting the following option:
mongoose.set("strictQuery", false);
mongoose.connect(process.env.MONGO_URL);
Since you are setting the mode before creating the connection, the mode will be enabled globally.
If you have any questions, feel free to comment below.