Connect to the MongoDB database
Connecting to MongoDB Database
MongoDB, as a popular NoSQL database, can greatly simplify data operations when paired with the Mongoose library in the Node.js ecosystem. Understanding core concepts such as connection strings, connection options, and connection events is essential for connecting to MongoDB using Mongoose.
Basic Connection Method
The simplest way to connect requires only the MongoDB URI:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase')
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Connection error:', err));
The connection string format is typically mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]
. When authentication is required:
mongoose.connect('mongodb://user:pass@localhost:27017/mydatabase?authSource=admin');
Connection Options Configuration
Mongoose supports a wide range of connection options:
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
poolSize: 10, // Connection pool size
connectTimeoutMS: 5000, // Connection timeout
socketTimeoutMS: 45000, // Socket timeout
family: 4, // Force IPv4
authSource: 'admin',
user: 'myUser',
pass: 'myPassword'
};
mongoose.connect('mongodb://localhost:27017/mydatabase', options);
Key options explained:
useNewUrlParser
: Use the new URL parseruseUnifiedTopology
: Use the new topology engineautoIndex
: Whether to automatically create indexes (recommendedfalse
for production)
Connection Pool Optimization
Connection pool management is critical for performance:
const options = {
poolSize: 20, // Default is 5
maxPoolSize: 100, // Maximum pool size
minPoolSize: 10, // Minimum pool size
serverSelectionTimeoutMS: 5000, // Server selection timeout
heartbeatFrequencyMS: 10000 // Heartbeat frequency
};
Monitoring connection pool status:
mongoose.connection.on('connected', () => {
console.log(`Mongoose default connection pool size: ${mongoose.connection.poolSize}`);
});
Multiple Database Connections
Real-world projects often require connections to multiple databases:
const db1 = mongoose.createConnection('mongodb://localhost:27017/db1');
const db2 = mongoose.createConnection('mongodb://localhost:27017/db2');
db1.on('open', () => console.log('DB1 connected'));
db2.on('open', () => console.log('DB2 connected'));
// Create models using different connections
const User = db1.model('User', userSchema);
const Product = db2.model('Product', productSchema);
Connection Event Handling
Mongoose connection lifecycle events:
mongoose.connection.on('connecting', () => {
console.log('Attempting to connect to MongoDB...');
});
mongoose.connection.on('connected', () => {
console.log('MongoDB connection established');
});
mongoose.connection.on('disconnected', () => {
console.log('MongoDB connection lost');
});
mongoose.connection.on('reconnected', () => {
console.log('MongoDB reconnected');
});
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});
Connection Retry Strategy
Automatic reconnection for unstable networks:
const options = {
autoReconnect: true, // Deprecated, enabled by default in newer versions
reconnectTries: Number.MAX_VALUE, // Infinite retries
reconnectInterval: 1000 // Retry interval
};
function connectWithRetry() {
return mongoose.connect(uri, options)
.catch(err => {
console.error('Connection failed, retrying in 5 seconds:', err.message);
return new Promise(resolve =>
setTimeout(() => connectWithRetry().then(resolve), 5000)
);
});
}
TLS/SSL Connection
Secure connection configuration example:
const fs = require('fs');
const options = {
ssl: true,
sslValidate: true,
sslCA: fs.readFileSync('./ca.pem'),
sslCert: fs.readFileSync('./client.pem'),
sslKey: fs.readFileSync('./client.key'),
sslPass: 'yourpassphrase'
};
mongoose.connect(uri, options);
Connection State Check
Utility function example:
function checkConnectionState() {
const states = {
0: 'Disconnected',
1: 'Connected',
2: 'Connecting',
3: 'Disconnecting',
99: 'Uninitialized'
};
return states[mongoose.connection.readyState];
}
// Usage example
console.log(`Current connection state: ${checkConnectionState()}`);
Connection Performance Optimization
Recommended configuration for production:
const prodOptions = {
autoIndex: false, // Disable auto-indexing in production
bufferCommands: false, // Disable buffering
bufferMaxEntries: 0, // Disable buffered entries
useCreateIndex: true, // Use createIndex() instead of ensureIndex()
useFindAndModify: false // Use native findOneAndUpdate()
};
Connection String Advanced Usage
Sharded cluster connection example:
const shardUri = 'mongodb://mongos1.example.com:27017,mongos2.example.com:27017/dbname?replicaSet=shard-rs';
Atlas cloud database connection:
const atlasUri = 'mongodb+srv://cluster0.mongodb.net/dbname?retryWrites=true&w=majority';
Connection Debugging
Enable debug mode for detailed logs:
mongoose.set('debug', true);
// Or customize debug function
mongoose.set('debug', (collectionName, method, query, doc) => {
console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});
Connection Closure
Proper way to close connections:
async function gracefulShutdown() {
await mongoose.connection.close();
console.log('MongoDB connection closed');
process.exit(0);
}
process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
Connection Middleware
Extend connection functionality with plugins:
// Define plugin
function connectionLogger(schema) {
schema.post('init', doc => {
console.log(`Document initialized from MongoDB: ${doc._id}`);
});
}
// Apply to connection
mongoose.plugin(connectionLogger);
Connection Best Practices
- Use environment variables for connection configuration:
require('dotenv').config();
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
- Implement a health check endpoint:
app.get('/health', (req, res) => {
if (mongoose.connection.readyState === 1) {
res.status(200).json({ status: 'OK' });
} else {
res.status(503).json({ status: 'DB disconnected' });
}
});
- Connection timeout handling:
const connectWithTimeout = async () => {
const timeout = setTimeout(() => {
throw new Error('Database connection timeout');
}, 5000);
await mongoose.connect(uri);
clearTimeout(timeout);
};
Connection Troubleshooting
Common error handling:
mongoose.connect(uri).catch(err => {
if (err.name === 'MongoNetworkError') {
console.error('Network issue:', err.message);
} else if (err.name === 'MongooseServerSelectionError') {
console.error('Server selection failed:', err.message);
} else if (err.name === 'MongoError' && err.code === 18) {
console.error('Authentication failed:', err.message);
}
});
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:使用npm安装Mongoose
下一篇:连接池配置与优化