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)
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.
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'}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With