node.js - Polymorphic associations with SailsJS -


i use sailsjs built rest api , takes advantage of blueprints.

my design has lot of resource in 1 asset resource :

asset ( id, type, owner_type, owner_id, url); 

this act entry point host multiple assets other resource in system.

ie.

user resource can have multiple images , video. of these records gets stored under asset resource.

asset ( id, type, owner_type, owner_id, url); asset ( 1, 'image', 'user', 1, 'http://path.to.image.com/abc.jpg'); asset ( 2, 'video', 'user', 1, 'https://youtube.com/sdasd'); asset ( 3, 'image', 'blogpost', 20, 'http://path.to.image.com/blogpost.jpg'); 

so ideally when user id or users , prefer related assets object.

its possible prepare response if implementing 2 methods getone , getall , when consuming blueprints bit blurred.

if understand correct, have user model, have asset model.

the user model looks

//user.js module.exports={     assets:{collection:'asset',via:'owner_id'} } 

the asset model should looks

module.exports={     type:'string',     owner_type:'string',     owner_id:{model:'user'},     url:'string' } 

you not able use blueprint directly, this:

//usercontroller.js module.exports={     findone:function(req,res){         user.findone(req.param.id).populate('assets',{owner_type:'user'}).exec(function(data){res.json(data)});     },     find:function(req,res){        user.find().populate.....//same idea    }  } 

this populate parameter {owner_type} populate options, populate collection of assets, has owner_type "user", can specify limit, documentation here, unfortunately didn't find official documentations this, sails , waterline still young framework, lots of unclear documentations , stuff, think have made right choice using it. let me know if helps.

edit: work user, if have blog model need populate it, can manually

//blog.js var promise=require('bluebird'); module.exports={     findone:function(req,res){         promise.all([blog.findone(req.param.id),         asset.find({owner_id:req.param.id,owner_type:'blog'})])         .spread(function(blog,assets){             blog.assets=assets             return req.json(blog);         })     } } 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -