简体   繁体   中英

Sequelize n:m association - Voting system - cannot set attribute of join table

I'm trying to implement a voting system so users of my app can vote on other users responses to a question.

It is a Node app using Express and Sequelize on the back-end, for the moment I'm using a SQLite database for ease of testing.

Here's the relevant parts of my models:

// in user.js
User.associate = function (models) {
  // ...
  models.User.belongsToMany(models.Response, {
    through: models.Vote,
    as: 'Votes'
  })
}

// in response.js
Response.associate = function (models) {
  // ...
  models.Response.belongsToMany(models.User, {
    through: models.Vote,
    as: 'Votes'
  })
}

// in vote.js
module.exports = (sequelize, DataTypes) => {
  return sequelize.define('Vote', {
    upVote: {
      type: DataTypes.BOOLEAN,
      allowNull: false
    }
  })
}

So now in my votes.js controller file I may try and create a new vote, given a UserId and a ResponseId as so:

const user = await User.findById(req.user.id)
const response = await Response.findById(req.params.responseId)

await response.addVote(user, {
  upVote: true
})

res.send(await response.getVotes())

The problem is, although the Votes join table is created correctly, and although I am passing the addVote function a boolean directly indicating what value the upVote attribute should store, I just get an error stating that notNull Violation: Vote.upVote cannot be null .

The only reason I added the not null constraint to begin with was because without it, I just received a vote with a null value for upVote .

Does anyone have any idea why this might be happening?

I don't know exactly why, but replacing the response.addVote with this:

const vote = await Vote.create({
  upVote: req.body.upVote,
  UserId: req.user.id,
  ResponseId: req.params.responseId
})

res.send(vote)

Works fine. Odd. I keep running into issues where the so-called 'magic' auto-generated functions that Sequelize is supposed to provide for relations either aren't available or don't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM