Skip to content

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:

none
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:

none
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

1. Correct strictQuery Setup

Set strictQuery before establishing database connection:

js
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:

js
// 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:

js
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:

js
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

  1. Order matters:

    • Always set strictQuery before calling mongoose.connect()
    • Configuration options need to be applied to the connection
  2. Connection handling:

    • Use IP 127.0.0.1 instead of localhost
    • Verify MongoDB service is running
    • Check port accessibility (default 27017)
  3. 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

  1. Set strictQuery explicitly at app startup
  2. Use 127.0.0.1 for local connections
  3. Handle connection events and errors
  4. Secure connections with environment variables
  5. Verify MongoDB service status (mongod)

Connection Pitfalls

  • Avoid mixing localhost and 127.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.