Technology Encyclopedia Home >How to use mongoose to connect to the cloud database MongoDB?

How to use mongoose to connect to the cloud database MongoDB?

To use Mongoose to connect to a cloud-hosted MongoDB database, follow these steps:

  1. Install Mongoose:
    First, install Mongoose in your Node.js project using npm:

    npm install mongoose
    
  2. 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
    
  3. 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));
    
  4. Example with Tencent Cloud Database for MongoDB:
    If you're using Tencent Cloud Database for MongoDB, ensure:

    • The connection string is correctly configured with your username, password, and cluster details.
    • Network access is allowed (e.g., whitelist your server IP in the Tencent Cloud console).
    • SSL is enabled if required by the provider.
  5. 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.