How to get the name of the model or model indicator of the waterline?

Unlike the previous question I asked here, it is connected and I really wanted to connect it.

I tried very hard to find out how I can get the name of the model (personality) or the model "class" (set in sails.models) of the record. So, given the record waterline, how can I find out her model name or class?

Example (of course, here I know what the model is User, but this is an example):

User.findOne(1).exec(function(err, record) {
  // at this point think that we don't know it a `user` record
  // we just know it some record of any kind
  // and I want to make some helper so that:
  getTheModelSomehow(record);
  // which would return either a string 'user' or the `User` pseudo-class object
});

I tried to access it with record.constructor, but it is not User, and I could not find any property on recordby exposing the object to the pseudo-class of the model or the name of the recording model.

UPDATE: To clarify, I need a function for which I will give ANY record, and which will return the model of this record either as the model name or an object of the model pseudo-class, as in the namespace sails.models.

modelForRecord(record) // => 'user' (or whatever string being the name of the record model)

or

modelForRecord(record) // => User (or whatever record model)
+4
source share
4 answers

WOW, well, after several hours of research, here's how I do it for those who are interested (this is a very difficult hack, but currently unable to find another way to do it):

, record - , findOne, create,... , , , , , (sails.models.*) instanceof :

function modelFor(record) {
  var model;
  for (var key in sails.models) {
    model = sails.models[key];
    if ( record instanceof model._model.__bindData__[0] ) {
      break;
    }
    model = undefined;
  }
  return model;
}

instanceof model,

, , modelFor(record).globalId, .

+7

. . , JSON.

module.exports = {
 attributes : {
      model : {type:'string',default:'User'}
 }
}
+1

. :

var model = req.options.model || req.options.controller;

. , model .

var Model = req._sails.models[model];

Check the source code to see it in action. ( https://github.com/balderdashy/sails/blob/master/lib/hooks/blueprints/actionUtil.js#L259 )

0
source

Use this example to parse a model name.

var parseModel = function(request) {
    request = request.toLowerCase();
    return sails.models[request];
};

and use this code in the controller to use this model

 parseModel(req.param('modelname')).find().then().catch();
0
source

All Articles