node.js - 与 SailsJS 的多态关联

标签 node.js sails.js

我使用 sailsJS 构建了一个利用蓝图的 REST API。

我的设计有很多资源,其中一个是 Assets 资源:

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

这将充当系统中任何其他资源托管多个 Assets 的入口点。

即。

用户资源可以有多个图像和一个视频。所有这些记录都存储在 Assets 资源下。

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');

因此,理想情况下,当我通过 ID 获取用户或获取所有用户时,我更愿意获取该对象的相关 Assets 。

如果我实现 GetOne 和 GetAll 的两种方法,则可以准备响应,但在使用蓝图时,它有点模糊。

最佳答案

如果我理解正确,那么您有用户模型,那么您就有 Assets 模型。

用户模型看起来像

//User.js
module.exports={
    assets:{collection:'Asset',via:'owner_id'}
}

Assets 模型应该看起来像

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

您将无法直接使用蓝图,但您可以执行以下操作:

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

}

这个填充参数{owner_type}是填充选项,这样它只填充 Assets 集合,其中owner_type是“User”,你也可以指定限制,如文档here ,不幸的是我没有找到这方面的官方文档,sails 和 Waterline 仍然是一个年轻的框架,有很多不清楚的文档和东西,但我认为你使用它做出了正确的选择。如果有帮助请告诉我。

编辑:这仅适用于用户,如果您有博客模型也需要填充它,那么您可以手动完成

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

关于node.js - 与 SailsJS 的多态关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30820419/

相关文章:

node.js - 在类中排序 RESTful API 方法的最佳实践

database - 为什么 Postgres 会在空表上引发唯一约束冲突?

angularjs - 如何在 Angular View 中获取 Node 当前用户

mysql - sequelize.js orm :Unique email validation for mysql not working

Node.js mailgun 内联/嵌入图像

javascript - 在nodejs中迭代项目数组

node.js - 聚合返回空数组 - Mongoose

node.js - 在nodejs中使用Multer上传文件

javascript - 如何让这个服务器进程永远运行呢?

node.js - 无法安装Waterlock