Search code examples
javascriptnode.jsexpressmongoosejavascript-objects

dynamic object creation via url


Trying to create a new instance of a mongoose model dynamically via a url request uisng express.

In the below example if const kind = 'modelOne' via the url I get 'Cannot read property 'modelOne' of undefined. Must be something up here but I cant figure it out.

const { modelOne } = require('./modelOne');
const { modelTwo } = require('./modelTwo');
const { modelThree } = require('./modelThree');

function response(req, res) {
 const kind = req.body.kind;
 const object = new this[kind] ({
  text: req.body
 });
};

Solution

  • First of all I wouldn't recommend you doing it this way even if it could work. It's always better not to trust the data you're getting in your requests. Try rather switch or sth like this:

    const { modelOne } = require('./modelOne');
    const { modelTwo } = require('./modelTwo');
    const { modelThree } = require('./modelThree');
    const models = {modelOne, modelTwo, modelThree}
    
    function response(req, res) {
     const kind = req.body.kind;
     const object = new models[kind] ({
      text: req.body
     });
    };
    

    The object referenced by this doesn't contain all the imported modules. I guess you're using Express so this === global. Try putting console.log(this) to the function and you'll see what all fields it contains.