将部分结果数据推送到数组中并发送

时间:2017-09-24 15:31:33

标签: mysql node-mysql

我有一个MySQL表,其中列名为tags,类型为VARCHAR。我用逗号分隔插入数据:

tag1, tag2, tag3, tag4, tag5, tag6

我的节点查询是:

app.get('/tagtest', (req, res) => {

    var tags = [];       // <= Not sure if I need this or how to push tags here.

    connection.query("SELECT * FROM tagtestpost", (err, rows)=>{
        res.send(rows)
    });

}); 

以上查询的回复是:

[{"id":1,"tags":"tag1, tag2, tag3"},{"id":2,"tags":"tag2, tag4"}]

我想在数组中返回标记。所以response应该是这样的:

[{"id":1,"tags":[tag1, tag2, tag3]},{"id":2,"tags":[tag2, tag4]}]

我怎样才能做到这一点?

UPDATE1

app.get('/showtagposts', (req, res) => {

    connection.query("SELECT * FROM postwithtagtest", (err, rows)=>{

        var a = rows;

    const expected = a.map((post) => ({
        ...post,
        tags: post.tags.split(/,\s+/)
    }));

    console.log(expected);

            res.json(expected);
    });

});

2 个答案:

答案 0 :(得分:2)

这不是 MySQL 实现您想要的方式。我有 JS 方式来实现您的需求。

    var a = [{"id":1,"tags":"tag1, tag2, tag3"},{"id":2,"tags":"tag2, tag4"}];
    var expected =[];
    a.forEach( function (eachObj){
        var obj = {};
        for (var key in eachObj) {
            if (eachObj.hasOwnProperty(key) && key ==='tags'){
                obj[key] = [eachObj[key]];
            }else{
                obj[key] = eachObj[key];
            }
        }
        expected.push(obj);
    });

    console.log(expected);

答案 1 :(得分:1)

接受的答案实际上并没有将标签拆分为数组中的单独值。以下是:

&#13;
&#13;
    const a = [{"id":1,"tags":"tag1, tag2, tag3"},{"id":2,"tags":"tag2, tag4"}];

    // ES6
    const expected = a.map((post) => ({
        ...post,
        tags: post.tags.split(/,\s+/)
    }));

    // ES5
    const expected = a.map(function (post) {
        return Object.assign({}, post, {
            tags: post.tags.split(/,\s+/)
        });
    });

    console.log(expected);
&#13;
&#13;
&#13;

<强>更新

使用Node时,spread运算符似乎不能与object一起使用。见这里:Node v6 failing on object spread

我已将其更改为使用Object.assign

app.get('/showtagposts', (req, res) => {
    connection.query("SELECT * FROM postwithtagtest", (err, rows) => {
        const data = rows.map((post) => {
            return Object.assign({}, post, {
                tags: post.tags.split(/,\s+/)
            });
        });

        res.json(data);
    });
});