Skip to content

Commit c4377c9

Browse files
fix(mdb): update code samples
1 parent da71f15 commit c4377c9

File tree

1 file changed

+93
-42
lines changed

1 file changed

+93
-42
lines changed

pages/managed-mongodb-databases/how-to/connect-database-instance.mdx

Lines changed: 93 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,10 @@ const databaseName = 'databaseName'
128128
// Path to your TLS certificate file
129129
const tlsCertificatePath = path.resolve(__dirname, 'path/to/your_tls_certificate.pem');
130130

131-
// Construct the connection string
132-
const connectionString = `mongodb+srv://${username}:${password}@${instanceId}.mgdb.${region}.scw.cloud`;
131+
// Construct the public connection string
132+
const connectionString = `mongodb+srv://${username}:${password}@${instanceId}.mgdb.${region}.scw.cloud;`
133+
// Construct the private connection string
134+
const connectionString = `mongodb+srv://${username}:${password}@${instanceId}.${privateNetworkId}.internal;`
133135

134136
// Create a new MongoClient
135137
const client = new MongoClient(connectionString, {
@@ -172,50 +174,96 @@ package main
172174

173175
import (
174176
"context"
177+
"crypto/tls"
178+
"crypto/x509"
175179
"fmt"
180+
"io/ioutil"
181+
"log"
182+
176183
"go.mongodb.org/mongo-driver/mongo"
177184
"go.mongodb.org/mongo-driver/mongo/options"
178185
)
179186

180187
func main() {
188+
// Replace with your MongoDB connection details
189+
username := "your_username"
190+
password := "your_password"
191+
instanceID := "your_instance_id" // your instance_id
192+
privateNetworkID := "your_private_network_id" // Id of your Private Network
193+
region := "your_region" // the region of your database instance. "fr-par" for Paris.
194+
tlsCertificate := "path/to/your_tls_certificate.pem" // path to your TLS certificate
195+
databaseName = "databaseName"
196+
197+
// Read CA certificate
198+
caCert, err := ioutil.ReadFile(tlsCertificate)
199+
if err != nil {
200+
log.Fatalf("Erreur lors de la lecture du fichier CA: %v", err)
201+
}
181202

182-
username := "<replace_with_user_name>"
183-
password := "<replace_with_password>"
184-
host := "<endpoint ip>"
185-
port := 1234 // replace with endpoint port number
186-
caCertPath := "<instance_certificate.crt>"
187-
// prepare the uri for the connection
188-
uri := fmt.Sprintf(
189-
"mongodb://%s:%s@%s:%d/rdb?tls=true&tlsCACert=%s&authMechanism=PLAIN",
190-
username,
191-
password,
192-
host,
193-
port,
194-
caCertPath,
195-
)
196-
ctx := context.Background()
197-
// connect to the database
198-
client, _ := mongo.Connect(ctx, options.Client().ApplyURI(uri))
199-
// get the database
200-
db := client.Database("rdb")
201-
// get the collection
202-
cars := db.Collection("cars")
203-
// insert a document
204-
carToInsert := Car{Name: "Supercar", Year: 2020}
205-
cars.InsertOne(ctx, carToInsert)
206-
207-
// read the document
208-
carToRead := Car{}
209-
cars.FindOne(ctx, map[string]interface{}{"name": "Supercar"}).Decode(&carToRead)
210-
211-
// print the document
212-
fmt.Println(carToRead)
203+
// Create certificate pool
204+
caCertPool := x509.NewCertPool()
205+
caCertPool.AppendCertsFromPEM(caCert)
213206

214-
}
207+
tlsConfig := &tls.Config{
208+
RootCAs: caCertPool,
209+
}
210+
211+
// Construct the public connection string
212+
connectionString := fmt.Sprintf("mongodb+srv://%s:%s@%s.mgdb.%s.scw.cloud", username, password, instanceID, region)
213+
// Construct the private connection string
214+
connectionString := fmt.Sprintf("mongodb+srv://%s:%s@%s.%s.internal", username, password, instanceID, privateNetworkID)
215+
216+
// Create a new client and connect to the server
217+
clientOptions := options.Client().
218+
ApplyURI(connectionString).
219+
SetTLSConfig(tlsConfig)
220+
client, err := mongo.Connect(context.TODO(), clientOptions)
221+
222+
if err != nil {
223+
log.Fatal(err)
224+
}
225+
226+
// Check the connection
227+
err = client.Ping(context.TODO(), nil)
228+
229+
if err != nil {
230+
log.Fatal(err)
231+
}
232+
233+
fmt.Println("Connected to MongoDB!")
215234

216-
type Car struct {
217-
Name string
218-
Year int
235+
// Access a specific collection
236+
collection := client.Database(databaseName).Collection("your_collection_name")
237+
238+
// Example: Find documents in the collection
239+
cursor, err := collection.Find(context.TODO(), map[string]interface{}{})
240+
241+
if err != nil {
242+
log.Fatal(err)
243+
}
244+
245+
defer cursor.Close(context.TODO())
246+
247+
for cursor.Next(context.TODO()) {
248+
var result map[string]interface{}
249+
err := cursor.Decode(&result)
250+
if err != nil {
251+
log.Fatal(err)
252+
}
253+
fmt.Println(result)
254+
}
255+
256+
if err := cursor.Err(); err != nil {
257+
log.Fatal(err)
258+
}
259+
260+
// Close the connection once no longer needed
261+
err = client.Disconnect(context.TODO())
262+
if err != nil {
263+
log.Fatal(err)
264+
}
265+
266+
fmt.Println("Connection to MongoDB closed.")
219267
}
220268
```
221269

@@ -227,28 +275,31 @@ The following code shows you how to use the `Mongoose` schema to connect using T
227275
const mongoose = require('mongoose');
228276
const path = require('path');
229277

230-
// Replace with your MongoDB® connection details
278+
// Replace with your MongoDB connection details
231279
const username = encodeURIComponent('your_username');
232280
const password = encodeURIComponent('your_password');
233-
const region = "your_region" // "fr-par" for Paris.
281+
const region = "your_region"; // "fr-par" for Paris.
234282
const instanceId = 'your_instance_id'; // your instance id
283+
const privateNetworkId = 'your_private_network_id'; // your private network id
235284
const databaseName = 'databaseName'
236285

237286
// Path to your TLS certificate file
238287
const tlsCertificatePath = path.resolve(__dirname, 'path/to/your_tls_certificate.pem');
239288

240-
// Construct the connection string
289+
// Construct the public connection string
241290
const connectionString = `mongodb+srv://${username}:${password}@${instanceId}.mgdb.${region}.scw.cloud`;
291+
// Construct the private connection string
292+
const connectionString = `mongodb+srv://${username}:${password}@${instanceId}.${privateNetworkId}.internal`;
242293

243-
// Connect to MongoDB® using Mongoose
294+
// Connect to MongoDB using Mongoose
244295
mongoose.connect(connectionString, {
245296
useNewUrlParser: true,
246297
useUnifiedTopology: true,
247298
tls: true, // Enable TLS/SSL
248299
tlsCAFile: tlsCertificatePath, // Path to the CA certificate file
249300
})
250301
.then(() => {
251-
console.log('Connected to MongoDB® with Mongoose!');
302+
console.log('Connected to MongoDB with Mongoose!');
252303
})
253304
.catch(err => {
254305
console.error('Connection error', err);

0 commit comments

Comments
 (0)