【问题标题】:Include ressource link in Sequelize result在 Sequelize 结果中包含资源链接
【发布时间】:2019-01-25 19:41:04
【问题描述】:

我正在构建一个使用 Sequelize 与数据库交互的 rest api。查询如下所示:

function read_category(req, res) {
    Category.findById(req.params.categoryId, {rejectOnEmpty: true}).then(category => {
        res.json(category);
    }).catch(Sequelize.EmptyResultError, function () {
            res.status(404).json({message: 'No category found'});
        }
    ).catch(function (err) {
            res.send(err);
        }
    );
}

现在我想要从 Sequelize 返回然后返回给用户的类别对象以将 link 包含到资源中。我可以这样做:

category.dataValues.link = config.base_url + 'categories/' + category.dataValues.id;

这会导致:

{
    "id": 1,
    "name": "TestCategory 1",
    "position": 1,
    "createdAt": "2018-08-19T11:42:09.000Z",
    "updatedAt": "2018-08-19T11:42:09.000Z",
    "link": "http://localhost:3000/categories/1"
}

由于我的路线比这条路线多,我想知道是否有一种动态方法可以将链接属性添加到每个类别。我不想将它保存在数据库中,因为 base-url 可能不同。

谢谢!

【问题讨论】:

    标签: json node.js rest sequelize.js


    【解决方案1】:

    更好的方法是,创建一个getter 方法

    const Category = sequelize.define( 'category' , {
        ....
        your_fields
        ....
    },
    {    
        getterMethods:{
            link() {
                return config.base_url + 'categories/' + this.id;
            }
        }
    });
    
    module.exports = Category;
    

    那么

    Category.findAll(...).then(categories => {
        // Now there is no need to append data manually , it will added each time when you query 
        console.log(categories); // <-- Check the output
    })
    

    【讨论】:

    • 谢谢您,先生!这就是我想要的 100%。
    猜你喜欢
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多