mysql - Node.js 用 mysql 编写 api 代码(sequelize)

标签 mysql json node.js api sequelize.js

我的 mysql 表 模型 :

//mysql
//table structures start

var Contact = sequelize.define('contact', {
    gsm: {
        type: Sequelize.STRING,
        unique: true,
        required: true
    },
    firstName: Sequelize.STRING,
    lastName: Sequelize.STRING,
    street: Sequelize.STRING,
    city: Sequelize.STRING,
})

var Group = sequelize.define('group', {
    groupname: Sequelize.STRING

})

var ContactGroup = sequelize.define('contactgroup', {
    /* Empty */
})

ContactGroup.belongsTo(Contact, {
    onDelete: 'CASCADE'
});

Contact.hasMany(ContactGroup, {
    onDelete: 'CASCADE'
});

ContactGroup.belongsTo(Group, {
    onDelete: 'CASCADE'
});
Group.hasMany(ContactGroup, {
    onDelete: 'CASCADE'
});

这是我的 第一个 api 代码:
exports.getNewGroup = (req, res) => {
    Group.findAll({
        attributes: ['id', 'groupname', [sequelize.fn('COUNT', sequelize.col('contactgroups.groupId')), 'contactsCount']],
        include: [{
            model: ContactGroup,
            attributes: ['id']
        }],
        group: ['id']
    }).then(data => {
        return res.status(200).send(data);
    }).catch(err => {
        return res.status(400).send(err.message);
    });
};

我得到了这样的第一个 api 响应:
[
    {
        "id": 14,
        "groupname": "Angular",
        "contactsCount": 2,
        "contactgroups": [
            {
                "id": 1
            }
        ]
    },
    {
        "id": 15,
        "groupname": "React",
        "contactsCount": 1,
        "contactgroups": [
            {
                "id": 3
            }
        ]
    },
    {
        "id": 16,
        "groupname": "Vue",
        "contactsCount": 0,
        "contactgroups": []
    },
    {
        "id": 17,
        "groupname": "NodeJs",
        "contactsCount": 0,
        "contactgroups": []
    },
    {
        "id": 18,
        "groupname": "RxJS",
        "contactsCount": 0,
        "contactgroups": []
    }
]

这是我的 第二个 api 代码:
exports.getNewGroupForProfsms = (req, res) => {
    Group.findAll({
        include: [{
            model: ContactGroup,
            attributes: ['id'],
            include: [{
                model: Contact,
                attributes: ['id', 'gsm']
            }]
        }],
    }).then(data => {
        return res.status(200).send(data);
    }).catch(err => {
        return res.status(400).send(err.message);
    });
};

这是我的第二个 api 响应:
[
    {
        "id": 14,
        "groupname": "Angular",
        "createdAt": "2017-12-15T15:06:39.000Z",
        "updatedAt": "2017-12-15T15:06:39.000Z",
        "contactgroups": [
            {
                "id": 1,
                "contact": {
                    "id": 20,
                    "gsm": "987654321"
                }
            },
            {
                "id": 2,
                "contact": {
                    "id": 21,
                    "gsm": "123456789"
                }
            }
        ]
    },
    {
        "id": 15,
        "groupname": "React",
        "createdAt": "2017-12-15T15:06:45.000Z",
        "updatedAt": "2017-12-15T15:06:45.000Z",
        "contactgroups": [
            {
                "id": 3,
                "contact": {
                    "id": 21,
                    "gsm": "123456789"
                }
            }
        ]
    },
    {
        "id": 16,
        "groupname": "Vue",
        "createdAt": "2017-12-15T15:06:51.000Z",
        "updatedAt": "2017-12-15T15:06:51.000Z",
        "contactgroups": []
    },
    {
        "id": 17,
        "groupname": "NodeJs",
        "createdAt": "2017-12-17T16:07:38.000Z",
        "updatedAt": "2017-12-17T16:07:38.000Z",
        "contactgroups": []
    },
    {
        "id": 18,
        "groupname": "RxJS",
        "createdAt": "2017-12-21T05:50:50.000Z",
        "updatedAt": "2017-12-21T05:50:50.000Z",
        "contactgroups": []
    }
]

在上面的代码中,我写了两个api,现在我想写一个api,

我需要这种类型的响应:(我在第一个 api 响应中有 contactsCount ,我希望在第二个 api 响应中)

最后,我想要这种类型的响应与单个 api 代码:
[
    {
        "id": 14,
        "groupname": "Angular",
        "contactsCount": 2,
        "createdAt": "2017-12-15T15:06:39.000Z",
        "updatedAt": "2017-12-15T15:06:39.000Z",
        "contactgroups": [
            {
                "id": 1,
                "contact": {
                    "id": 20,
                    "gsm": "987654321"
                }
            },
            {
                "id": 2,
                "contact": {
                    "id": 21,
                    "gsm": "123456789"
                }
            }
        ]
    },
    {
        "id": 15,
        "groupname": "React",
        "contactsCount": 1,
        "createdAt": "2017-12-15T15:06:45.000Z",
        "updatedAt": "2017-12-15T15:06:45.000Z",
        "contactgroups": [
            {
                "id": 3,
                "contact": {
                    "id": 21,
                    "gsm": "123456789"
                }
            }
        ]
    },
    {
        "id": 16,
        "groupname": "Vue",
        "contactsCount": 0,
        "createdAt": "2017-12-15T15:06:51.000Z",
        "updatedAt": "2017-12-15T15:06:51.000Z",
        "contactgroups": []
    },
    {
        "id": 17,
        "groupname": "NodeJs",
        "contactsCount": 0,
        "createdAt": "2017-12-17T16:07:38.000Z",
        "updatedAt": "2017-12-17T16:07:38.000Z",
        "contactgroups": []
    },
    {
        "id": 18,
        "groupname": "RxJS",
        "contactsCount": 0,
        "createdAt": "2017-12-21T05:50:50.000Z",
        "updatedAt": "2017-12-21T05:50:50.000Z",
        "contactgroups": []
    }
]

有人会帮助我吗?我需要单个 api 代码。

我尝试了嵌套查询,并像这样修改了我的第一个 api 代码:
exports.getNewGroup = (req, res) => {
    Group.findAll({
        attributes: ['id', 'groupname', [sequelize.fn('COUNT', sequelize.col('contactgroups.groupId')), 'contactsCount']],
        include: [{
            model: ContactGroup,
            attributes: ['id'],
            include: [{
                model: Contact,
                attributes: ['id', 'gsm']
            }]
        }],
        group: ['id']
    }).then(data => {
        return res.status(200).send(data);
    }).catch(err => {
        return res.status(400).send(err.message);
    });
};

但我得到的不是我的要求
[
    {
        "id": 14,
        "groupname": "Angular",
        "contactsCount": 2,
        "contactgroups": [
            {
                "id": 1,
                "contact": {
                    "id": 20,
                    "gsm": "987654321"
                }
            }
        ]
    },
    {
        "id": 15,
        "groupname": "React",
        "contactsCount": 1,
        "contactgroups": [
            {
                "id": 3,
                "contact": {
                    "id": 21,
                    "gsm": "123456789"
                }
            }
        ]
    },
    {
        "id": 16,
        "groupname": "Vue",
        "contactsCount": 0,
        "contactgroups": []
    },
    {
        "id": 17,
        "groupname": "NodeJs",
        "contactsCount": 0,
        "contactgroups": []
    },
    {
        "id": 18,
        "groupname": "RxJS",
        "contactsCount": 0,
        "contactgroups": []
    }
]

最佳答案

试试这个代码

exports.getNewGroupForProfsms = (req, res) => {
  Group.findAll({
    include: [{
      model: ContactGroup,
      attributes: ['id'],
      include: [{
        model: Contact,
        attributes: ['id', 'gsm']
      }]
    }],
  }).then(data => {
    // change happen here
    return res.status(200).send(data.map((x) => {
      // assign contactsCount to each row
      return Object.assign({
        contactsCount: x.contactgroups.length,
      }, x.toJSON()) // update toJSON have a try
    }));
  }).catch(err => {
    return res.status(400).send(err.message);
  });
};

关于mysql - Node.js 用 mysql 编写 api 代码(sequelize),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47919818/

相关文章:

node.js - 关于自定义 node.js CLI 工具配置文件的建议/最佳实践 : location & naming?

mysql - 如何从现有的单表数据库填充合理的多表 MySQL 数据库?

php - 多个客户表或大型整体表

javascript - 如何从对象中获取值?

python - 将 json 对象转换为 python 中的数据框

javascript - 从 JSON 对象获取数组

mysql - 关于带有 order by 和 limit 的 select * 的可重复读取

mysql - 在重复键更新时每次插入记录

javascript - 如何让机器人响应 channel 提及?

javascript - 从同一文件中获取 module.exports