Sailsjs: dynamic tableName in model

Problem

I am building my first sailsjs and nodejs application, and it great :)

My situation, I have about 100 tables with the same stucture, I would like to decide "on the fly" which table to load.

my first thought was use somehow a dynamic class names. But I dont know how to do this with nodejs, maybe some one have an idea.

So I would create 100 "modelName".js files in my models folder.

I can use this in browser

window["fileName"].find()....

But I don't have any window object in nodejs

Second idea was to pass the tableName to the model, the problem is, I have to reinit the model, don't know how.

Any solutions?

Problem courtesy of: Fribu

Solution

Found a solution

var modelName = req.param('p');
this[modelName].find()...
Solution courtesy of: Fribu

Discussion

Own answer by author is correct, but I will add something just for people who will use it in the future - you can get modelName from req.options.model when you are using Blueprints.

Unfortunately you can't use this[modelName] as option is giving you model name starting with small letter, so first you have to upper case first letter with e.g. var modelName = req.options.model.charAt(0).toUpperCase() + req.options.model.slice(1);

and then you are free to use this[modelName].whateverYouNeed

I used it for generic policy to let user editing only his own group elements.

var modelName = req.options.model.charAt(0).toUpperCase() + req.options.model.slice(1)
  var elementID = null

  if (req.params.id) { // To handle DELETE, PUT
    elementID = req.params.id
  }
  if (req.body.id) { // To handle POST
    elementID = req.body.id
  }

  this[modelName].findOne({
    id: elementID
  }).exec(function(err, contextElement) {
    if(err) {
      return res.serverError(err)
    }
    if(contextElement.group=== req.user.group.id) {
      sails.log('accessing own: ' + modelName)
      return next()
    }
    else {
      return res.forbidden('Tried to access not owned object')
    }
  })
Discussion courtesy of: M U

Another option that worked for me:

var modelName = "User";
global[modelName].find()....
Discussion courtesy of: omegabloom

This recipe can be found in it's original form on Stack Over Flow.