aardvark28
aardvark28

Reputation: 1

Creating new instances for a Many to Many relationship using Sequelize

I am using NodeJS, Express, Sequelize and PostgreSQL.

I have two models. A "User" model and a "Social" model. I want a many to many relationship so a user can have many socials and a social can have many users.

This is the code I have so far. I understand that the "belongsToMany" creates a new Join table and I may be trying too much because this seems overly complicated.

models/user.js:

'use strict';
module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    username: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        User.belongsToMany(models.Social, {through: 'User_Social', foreignKey: 'User_rowId'})

      }
    }
  });
  return User;
};

models/social.js:

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Social = sequelize.define('Social', {
    title: DataTypes.STRING,
    description: DataTypes.TEXT
  }, {
    classMethods: {
      associate: function(models) {
        Social.belongsToMany(models.User, {through: 'User_Social', foreignKey: 'Social_rowId'})
      }
    }
  });
  return Social;
};

routes/users.js

router.post('/:UserId/socials', function(req, res) {
  userPromise = models.User.findById(req.params.UserId)

  userPromise.then(function(user) {
    models.Social.create({
    title: req.body.title,
    description: req.body.description
  })
  .then(function (social) {
    user.addSocials([social, social.id])
  })
  .then(function() {
    res.redirect('/');
  });  
  })


});

When I try to create a new social using the form on my website, this is the error I get in the console:

Unhandled rejection SequelizeUniqueConstraintError: Validation error
    at Query.formatError (meetup-app/node_modules/sequelize/lib/dialects/postgres/query.js:326:16)
    at null.<anonymous> (meetup-app/node_modules/sequelize/lib/dialects/postgres/query.js:88:19)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at Query.handleError (meetup-app/node_modules/pg/lib/query.js:131:8)
    at null.<anonymous> (meetup-app/node_modules/pg/lib/client.js:180:26)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at Socket.<anonymous> (meetup-app/node_modules/pg/lib/connection.js:121:12)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:146:16)
    at Socket.Readable.push (_stream_readable.js:110:10)
    at TCP.onread (net.js:523:20)

Any help would be appreciated!

Upvotes: 0

Views: 696

Answers (1)

kabochya
kabochya

Reputation: 1

The error is that you created two instances of social that have the same id, which should be unique. The correct way to add that associations is by user.addSocial(social).

Upvotes: 0

Related Questions