在Express中通过表格过帐数据以进行序列化

时间:2019-07-08 00:16:41

标签: javascript express sequelize.js

我有一个postgresql数据库设置,允许用户互相跟踪,我使用了一个贯通表来进行设置。

    as: 'follower',
    through: 'follow',
    foreignKey: 'follower_id'
})

User.belongsToMany(User, {
    as: 'following',
    through: 'follow',
    foreignKey: 'following_id'
})

表格:

| created_at | updated_at | follower_id | following_id |
|------------|------------|-------------|--------------|
|            |            |             |              |

我的获取请求:

userRouter.get('/:user_id/followers', async (req, res) => {
    try {
        const user = await User.findOne({
            where: {
                id: req.params.user_id
            },
            include: [
                {
                    model: User,
                    as: 'follower',
                    through: { attributes: [] }
                }
            ]
        })
        res.send(user)
    } catch (error) {
        console.log(error)
    }
})

结果:

{
  "id": 1,
  "firstName": "John",
  "lastName": "Smith",
  "username": "tester",
  "profileImage": null,
  "email": "tester@mail.com",
  "password": "$2b$12$h2rVqmxgsGxTOVgq3aII5uCuRcSN0TZZ6lwZgRRHCaOhu98K3AKbe",
  "skills": [
    "React",
    "Python",
    "Mongo"
  ],
  "createdAt": "2019-07-07T23:38:07.730Z",
  "updatedAt": "2019-07-07T23:38:07.730Z",
  "follower": []
}

现在,我陷入了如何使用发布或放置请求向该表添加新条目的问题。

1 个答案:

答案 0 :(得分:0)

经过一番修补,我找到了答案。

发布新关注者时遇到问题,它覆盖了现有条目。

这是我设置关联的方式:

const Follower = db.define('follower', {
    follower_id: {
        primaryKey: true,
        type: Sequelize.INTEGER
    }
})

Follower.belongsTo(User, {
    as: 'user',
    through: 'follower',
    foreignKey: 'follower_id'
})

User.hasMany(Follower, { as: 'followers' })

我的路线:

userRouter.get('/:user_id/followers', async (req, res) => {
    try {
        const user = await User.findOne({
            where: {
                id: req.params.user_id
            },
            include: [
                {
                    model: Follower,
                    as: 'followers',
                    include: [
                        {
                            model: User,
                            as: 'user'
                        }
                    ]
                }
            ]
        })
        res.send(user)
    } catch (error) {
        throw error
    }
})

发布路线:

userRouter.post('/:user_id/follow/:follower_id', async (req, res) => {
    try {
        const user = await User.findByPk(req.params.user_id)
        if (user) {
            if (user.id.toString() === req.params.follower_id) {
                res.status(400).json({ err: 'You cannot follow yourself' })
            } else {
                const following = await Follower.findOrCreate({
                    where: {
                        userId: req.params.user_id,
                        follower_id: req.params.follower_id
                    }
                })
                res.send(following)
            }
        }
    } catch (error) {
        throw error
    }
})

现在像魅力一样工作:

 follower_id |         created_at         |         updated_at         | user_id 
-------------+----------------------------+----------------------------+---------
           2 | 2019-07-07 23:36:06.696-04 | 2019-07-07 23:36:06.696-04 |       1
           3 | 2019-07-07 23:36:22.498-04 | 2019-07-07 23:36:22.498-04 |       1

来自api的数据:

{
  "id": 1,
  "firstName": "John",
  "lastName": "Smith",
  "username": "tester",
  "profileImage": null,
  "email": "tester@mail.com",
  "password": "$2b$12$0Ir/1zWRPvx3MWRjq6l85.z35QyCPwDqX7TyhAeWZHLx75RmGzlKS",
  "skills": [
    "React",
    "Python",
    "Mongo"
  ],
  "createdAt": "2019-07-08T03:36:00.262Z",
  "updatedAt": "2019-07-08T03:36:00.262Z",
  "followers": [
    {
      "follower_id": 2,
      "createdAt": "2019-07-08T03:36:06.696Z",
      "updatedAt": "2019-07-08T03:36:06.696Z",
      "userId": 1,
      "user": {
        "id": 2,
        "firstName": "Jane",
        "lastName": "Doe",
        "username": "test",
        "profileImage": null,
        "email": "test@mail.com",
        "password": "$2b$12$pxg9ssYtSIZm3TPcYDzjnOZApaFjXWPypM8et1m5nSPZeH1voGVHO",
        "skills": [
          "HTML",
          "Css",
          "React"
        ],
        "createdAt": "2019-07-08T03:36:00.519Z",
        "updatedAt": "2019-07-08T03:36:00.519Z"
      }
    },
    {
      "follower_id": 3,
      "createdAt": "2019-07-08T03:36:22.498Z",
      "updatedAt": "2019-07-08T03:36:22.498Z",
      "userId": 1,
      "user": {
        "id": 3,
        "firstName": "Jackie",
        "lastName": "Legs",
        "username": "test3",
        "profileImage": null,
        "email": "test3@mail.com",
        "password": "$2b$12$V0UgOVxB.c5/gbuUIqvvW.cnWqZjsqLUnHCgoT4zwzFtBPucgRAl2",
        "skills": [
          "HTML",
          "Css"
        ],
        "createdAt": "2019-07-08T03:36:00.758Z",
        "updatedAt": "2019-07-08T03:36:00.758Z"
      }
    }
  ]
}