'Create dynamic mongoDB models in classes with typescript

I would like to create a class with all CRUD operations to make them more reusable. The idea is set a dynamic models from mongodb and create an instance with the model I need.

Here is the code/idea:

type models = cart | orders | product | user;

class CRUD extends UserUtils {
   model : models;

    constructor(model: models) {
        super();
        this.model = model
    }

   create(req: any, res: any) {
       const newCart = new this.model(req.body);

   try {
      const savedCart = await newCart.save();
      res.status(200).json(savedCart);
   } catch (error) {
      res.status(500).json(error);
   }
}

I create an interface for each models (order, cart,...) and assigned it to a type.

I have an error at const newCart = new this.model(req.body) that says

This expression is not constructable. ts(2351)



Solution 1:[1]

I can see the whole code and the others files, but I don't see imports.

I'm junior as well, but I work a lot with MERN and based in my experience, I think that you have to import.

Have you tried with import * as models from 'file_path_of_your_models'.

I would like to help you more, I'll investigate this.

I hope I can help you :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rubdh