Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
How to use static class in Express

I'm new to the JavaScript world and I want to create a web app using the MEAN stack.

To keep my files organized (a little bit at least), I would like to keep all the MongoDb part in a static class a call it in my app.js file when I need it.

Here an example in C# (which is more familiar for me):

public static class Test
{
    public static void PrintHello()
    {
        Console.WriteLine("Hello world");
    }
}


static void Main(string[] args)
{
    Test.PrintHello();
}

app.js

let express = require('express');
let app = express();
// parser nécessaire pour récupérer les valeurs en mode POST
let bodyParser = require("body-parser");
const {MongoRequest} = require('./MongoRequest.js');
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(8888, () => {
    console.log('Server running at http://localhost:8888/')
});

app.get('/module/getAll', async (req, res) => { // GET
    try {
        console.log("Page d'accueil");
        let a = await MongoRequest.GetAllModules();
        console.log(a);
        res.send(a);
    } catch (error) {
        console.error(error);
        res.send(error.message);
    }
});

MongoRequest.js

class MongoRequest {

    static async CreateMongoClient(){
        let mongo = require('mongodb').MongoClient;
        let path = "mongodb://localhost:27017/GestionHeures";
        let client = new mongo(path);
        return client;
    }

    static async GetAllModules(){
        
        let retour;

        try {
            let client = await CreateMongoClient();
            client = await client.connect();
            
            let db = client.db("GestionHeures");

            retour = await db.collection("modules").find().toArray();

            //prom.then( r => {retour = r;});
            console.log("OK");
        } catch (e) {
            console.error(e);
        } finally {
            client.close();
        }
        return retour;
    }
}

module.exports = MongoRequest;

When I try with this I get this error :

TypeError: Cannot read properties of undefined (reading 'GetAllModules')

What am is wrong with my code

Thanks in advance

PS: If you have any advice to keep my code organized. I will be glad to take them

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

First of all, welcome to JavaScript!

It appears your CommonJS import const {MongoRequest} = require('./MongoRequest.js'); does not match your export

try importing like this:

const MongoRequest = require('./MongoRequest.js');

Since you are exporting the entire class you do not need to destructure it in your import. I hope this helps.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda