mongodb
Sunday 12 March 2023

connection with mongoDatabase

if mongo_uri not work write 127.0.0.1 instead of localhost

first download dependencies

npm i mongodb

second create db.ts file and write the following code

 1import { MongoClient } from 'mongodb';
 2import { MONGODB_URI, DATABASE_NAME } from './config';
 3
 4let connectedClient;
 5
 6export const connectClient = async () => {
 7  /// to use cached client
 8  if (connectedClient) {
 9    return connectedClient.db(DATABASE_NAME);
10  }
11  const client = new MongoClient(MONGODB_URI);
12  await client.connect();
13  await client.db(DATABASE_NAME).command({ ping: 1 });
14  console.info('database connected successfully');
15
16  connectedClient = client;
17
18  return connectedClient.db(DATABASE_NAME);
19};
20
21export const stopClient = async () => {
22  return connectedClient?.close();
23};
24

Backlinks