I want to make Node.js handler how can I do it?

Since I will be using it in more than one different file, I want to do the connect process in a short way, how can I do it? Sorry for the bad explanation.

Hello @HerrWinfried, welcome to the MongoDB Community forum!

This is a NodeJS application and uses ExpressJS for creating the web server. The MongoDB NodeJS Driver is used for connecting to the MongoDB Database Server.

There are two programs (modules) in the application. The main app.js to start the web server and the database server. Then, the db.js to get connection to the database server. After you get the first connection, the same connection can be used from any of the programs in the application.


const { MongoClient } = require("mongodb")
const uri = "mongodb://"
const opts = { useUnifiedTopology: true }

let connection

const connect = async () => {

	try {
		console.log("# Connecting to database server...")
		connection = await MongoClient.connect(uri, opts)
		console.log("# Connected")
	catch(err) {
		console.error("# Database connection error")
		throw err

module.exports = {

	getConnection: async () => {
		if (!connection) {
			await connect()
		return connection


const express = require("express")
const db = require("./db")
const app = express()

const startServers = async () => {
	try {
		await db.getConnection()
		app.listen(3000, () => {
    		console.log("# App server is running")
	catch(err) {
		console.log("# Error starting servers")


I need to select a database, extract, edit, delete data, how can I do that? Could you show an example, please?

Hello @HerrWinfried, you can select a database and perform the CRUD (Create, Read, Update and Delete) operations on the data - from a program or interactively using a tool.

mongosh is a command line tool and Compass is a desktop GUI tool.

You can perform the CRUD Operations using any of these two tools. The following link is about using the mongosh to perform the CRUD:

1 Like

Thanks for the information, how can I fix this?
after i fix this i will use findOne

var mongoDB = require("../mongodb.js");
var warnDB = mongoDB.getConnection().db("admin").collection('coltest');


var warnDB = mongoDB.getConnection().db("admin").collection('coltest');

TypeError: mongoDB.getConnection(...).db is not a function```

@HerrWinfried, The error is pointing to the NodeJS module mongodb.js . First, check the following statement: var mongoDB = require("../mongodb.js"); Next, check your code in the mongodb.js module. You can use my code or any online examples for comparison.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.