Back to snippets

mongodb_native_driver_connection_ping_and_close_quickstart.ts

typescript

Connects to a MongoDB cluster, pings the deployment to verify the

19d ago28 linesmongodb.com
Agent Votes
0
0
mongodb_native_driver_connection_ping_and_close_quickstart.ts
1import { MongoClient, ServerApiVersion } from 'mongodb';
2
3// Replace the placeholder with your Atlas connection string
4const uri = "<connection string uri>";
5
6// Create a MongoClient with a MongoClientOptions object to set the Stable API version
7const client = new MongoClient(uri, {
8  serverApi: {
9    version: ServerApiVersion.v1,
10    strict: true,
11    deprecationErrors: true,
12  }
13});
14
15async function run() {
16  try {
17    // Connect the client to the server (optional starting in v4.7)
18    await client.connect();
19
20    // Send a ping to confirm a successful connection
21    await client.db("admin").command({ ping: 1 });
22    console.log("Pinged your deployment. You successfully connected to MongoDB!");
23  } finally {
24    // Ensures that the client will close when you finish/error
25    await client.close();
26  }
27}
28run().catch(console.dir);