如何获取水线logging的模型名称或模型类?
虽然与我在前面提到的问题有所不同,但它是相关的,因此想要链接它。
我一直在努力研究如何获得logging的模型名称(标识)或模型“类” (在sails.models
中sails.models
)。 所以,如果有waterline
logging,我怎样才能find它的模型名称或类?
例子(当然,我知道模型是User
但是这是一个例子):
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 });
我试图用record.constructor
访问它,但这不是User
,我无法find任何record
暴露模型的伪类对象或logging的模型名称的属性。
更新: 为了澄清,我想要一个函数,我会给任何logging,哪些将返回该logging的模型作为模型名称或模型伪类对象在sails.models
命名空间。
modelForRecord(record) // => 'user' (or whatever string being the name of the record's model)
要么
modelForRecord(record) // => User (or whatever record's model)
WOW,经过几个小时的研究,好的,下面是我为那些感兴趣的人(这是一个非常棘手的黑客,但现在无法find另一种方式):
比方说, record
是你从findOne
得到的,在callback中create
…,找出它是什么样的实例,然后find拥有这个logging的模型的名字,你必须遍历所有的模型( 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
就可以得到它。
在你的模型定义中,为什么不只是创build一个模型属性。 然后,模型将随每个logging调用返回。 即使logging成为JSON对象,这也可以工作。
module.exports = { attributes : { model : {type:'string',default:'User'} } }
Sails公开了请求对象中的所有内容。 尝试用这种方法来获取模型的名称:
var model = req.options.model || req.options.controller;
这会给你的原始名称。 要使用它,您必须将model
插入到sails模型数组中。
var Model = req._sails.models[model];
查看源代码以查看它的行动。 ( https://github.com/balderdashy/sails/blob/master/lib/hooks/blueprints/actionUtil.js#L259 )
使用这个例子来parsing模型名称
var parseModel = function(request) { request = request.toLowerCase(); return sails.models[request]; };
并在控制器中使用这个代码来使用这个模型
parseModel(req.param('modelname')).find().then().catch();