To use Mongoose to connect to a cloud-hosted MongoDB database, follow these steps:
Install Mongoose:
First, install Mongoose in your Node.js project using npm:
npm install mongoose
Get the Cloud MongoDB Connection String:
Obtain the connection string (URI) from your cloud MongoDB provider (e.g., Tencent Cloud Database for MongoDB). The URI typically looks like:
mongodb+srv://<username>:<password>@cluster0.example.mongodb.net/<database>?retryWrites=true&w=majority
Connect Using Mongoose:
Use the following code to establish a connection:
const mongoose = require('mongoose');
const uri = 'mongodb+srv://<username>:<password>@cluster0.example.mongodb.net/<database>?retryWrites=true&w=majority';
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('Connection error:', err));
Example with Tencent Cloud Database for MongoDB:
If you're using Tencent Cloud Database for MongoDB, ensure:
Handling Disconnections and Reconnections:
Mongoose automatically handles reconnections, but you can add event listeners for better control:
mongoose.connection.on('connected', () => console.log('Mongoose connected'));
mongoose.connection.on('error', (err) => console.error('Mongoose error:', err));
mongoose.connection.on('disconnected', () => console.log('Mongoose disconnected'));
For Tencent Cloud Database for MongoDB, ensure you follow their security best practices, such as using VPC peering or private endpoints if available.