Mongoose supports a separate strictQuery
option to avoid strict mode for query filters. This is because empty query filters cause Mongoose to return all documents in the model, which can cause issues.
Reproducing the Issue
Run the project with Mongoose version 6.
npm start
Output
(node:7947) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)
Solution
Use node --trace-deprecation ...
to show where the warning was created.
Syntax
node --trace-deprecation <entryPoint>
Replace <entryPoint> with the name of your Node.js entry file.
Example
node --trace-deprecation app.js
Output
(node:8029) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
at Mongoose.connect (/home/developer/Documents/MongoDB/Projects/mongoose-jwt/node_modules/mongoose/lib/index.js:410:5)
at Object.<anonymous> (/home/developer/Documents/MongoDB/Projects/mongoose-jwt/models/connection.js:6:10)
at Module._compile (node:internal/modules/cjs/loader:1241:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
at Module.load (node:internal/modules/cjs/loader:1091:32)
at Module._load (node:internal/modules/cjs/loader:938:12)
at Module.require (node:internal/modules/cjs/loader:1115:19)
at require (node:internal/modules/helpers:130:18)
at Object.<anonymous> (/home/developer/Documents/MongoDB/Projects/mongoose-jwt/app.js:8:1)
at Module._compile (node:internal/modules/cjs/loader:1241:14)
In this case, you need to modify connection.js
file to include the mongoose.set('strictQuery', false);
statement. Add the mongoose.set('strictQuery', false);
statement before connection logic.
Example
const mongoose = require("mongoose");
const config = require("../config/database.config");
mongoose.set("strictQuery", false);
mongoose.connect(config.uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const conn = mongoose.connection;
conn.on("error", () => console.error("Connection Error"));
conn.once("open", () => console.info("Connection to Database is successful"));
module.exports = conn;
Conclusion
By adding the mongoose.set('strictQuery', false);
statement before connection logic, you will suppress the deprecation warning. In Mongoose 7, strictQuery
is false
by default.