Mongoose strictQuery
Deprecation Warning and Connection Fixes
Problem Statement
When setting up a MongoDB connection with Mongoose, you may encounter a deprecation warning related to the strictQuery
option:
DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7...
Additionally, you might see a timeout error when saving data:
MongooseError: Operation `fruits.insertOne()` buffering timed out after 10000ms
These errors occur due to:
- Mongoose 6's default
strictQuery: true
behavior preparing for a change - Incorrect connection configuration order
- Possible DNS resolution issues with
localhost
Understanding strictQuery
The deprecation warning alerts you about an upcoming change in Mongoose 7:
- Mongoose 6: Default
strictQuery: true
- Mongoose 7: Default will revert to
false
- To suppress the warning, explicitly set your preferred value
Recommended Solutions
1. Correct strictQuery
Setup
Set strictQuery
before establishing database connection:
const mongoose = require('mongoose');
// Must be placed BEFORE connect
mongoose.set('strictQuery', false); // Or true based on your needs
// Then connect
mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB', {
useNewUrlParser: true,
useUnifiedTopology: true
});
2. Fix Connection Timeout
Replace localhost
with 127.0.0.1
in your connection string:
// Before
mongoose.connect('mongodb://localhost:27017/fruitsDB');
// After (fixes DNS resolution issue)
mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB');
3. Robust Connection Handling
Implement error handling using async/await:
const connectDB = async () => {
try {
mongoose.set('strictQuery', false);
await mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB', {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log('MongoDB connected');
// Only save documents after connection success
const fruit = new Fruit({ name: 'Apple', rating: 7, review: 'Taste Good' });
await fruit.save();
console.log('Fruit saved successfully');
} catch (err) {
console.error('Database connection error:', err.message);
process.exit(1);
}
};
connectDB();
4. Production-ready Connection Template
Handle environment variables and connection events:
const mongoose = require('mongoose');
// Configuration best practices
mongoose.set('strictQuery', false);
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (err) {
console.error(`Connection failed: ${err.message}`);
process.exit(1);
}
};
// Connection event handlers
mongoose.connection.on('connecting', () => {
console.log('Connecting to MongoDB...');
});
mongoose.connection.on('disconnected', () => {
console.log('MongoDB disconnected!');
});
module.exports = connectDB;
Key Considerations
Order matters:
- Always set
strictQuery
before callingmongoose.connect()
- Configuration options need to be applied to the connection
- Always set
Connection handling:
- Use IP
127.0.0.1
instead oflocalhost
- Verify MongoDB service is running
- Check port accessibility (default 27017)
- Use IP
Security implications of
strictQuery
:js// strictQuery: true (recommended for new projects) new Fruit({ name: 'Apple', unknownField: 'test' }).save(); // Result: unknownField WON'T be saved // strictQuery: false new Fruit({ name: 'Apple', unknownField: 'test' }).save(); // Result: unknownField WILL be saved
Best Practices Summary
Production Checklist
- Set
strictQuery
explicitly at app startup - Use
127.0.0.1
for local connections - Handle connection events and errors
- Secure connections with environment variables
- Verify MongoDB service status (
mongod
)
Connection Pitfalls
- Avoid mixing
localhost
and127.0.0.1
- Don't place
mongoose.set()
after connection - Never run database operations before connection ready
By following these practices, you'll resolve both the deprecation warning and connection issues while ensuring your Mongoose configuration remains compatible with upcoming versions.