Search code examples
javascriptnode.jsmean-stack

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


Solution

  • 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.