Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the model name or model class of a waterline record?

While different from a previous question I asked here, it's related and so wanted to link it.

I have been trying hard to find out how I can get the model name (identity) or model "class" (exposed in sails.models) of a record. So, given a waterline record, how can I find out its model name or class?

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

User.findOne(1).exec(function(err, record) {
  // at this point think that we don't know it's a `user` record
  // we just know it's 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 have tried to access it with record.constructor but that is not User, and I couldn't find any property on record exposing either the model's pseudo-class object or the record's model name.

UPDATE: To clarify, I want a function to which I'll give ANY record, and which would return the model of that record as either the model name or the model pseudo-class object as in sails.models namespace.

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

or

modelForRecord(record) // => User (or whatever record's model)
like image 992
Huafu Avatar asked Jan 10 '23 14:01

Huafu


2 Answers

WOW, ok after hours of research, here is how I am doing it for those who are interested (it's a very tricky hack, but for now unable to find another way of doing):

Let's say record is what you get from a findOne, create, ... in the callback, to find out what instance it is, and so find the name of the model owning the record, you have to loop over all your models (sails.models.*) and make an instanceof call this way:

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;
}

Do not try to simply do instanceof model, that does not work

After if you need the model name simply modelFor(record).globalId to get it.

like image 120
Huafu Avatar answered Jan 25 '23 17:01

Huafu


In your model definition why not just create a model attribute. Then the model will be returned with every record call. This will work even after the record become a JSON object.

module.exports = {
 attributes : {
      model : {type:'string',default:'User'}
 }
}
like image 44
Meeker Avatar answered Jan 25 '23 17:01

Meeker