Create n:m objects using json and sequelize?

1.9k Views Asked by At

I am trying to learn sequelize, but am having trouble getting a n:m object created. So far I have my 2 models that create 3 tables (Store, Product, StoreProducts) and the models below:

models/Store.js

module.exports = (sequelize, DataTypes) => {
    return Store = sequelize.define('Store', {
        name: {
            type: DataTypes.STRING,
        },
        address: {
            type: DataTypes.STRING,
        }
    });
};

models/Product.js

module.exports = function(sequelize, DataTypes) {
  return Product = sequelize.define('Product', { 
        name: {
            type: DataTypes.STRING,
        }
  });
};

models/Index.js

 models.Store.belongsToMany(models.Products, {through: 'StoreProducts', foreignKey: 'storeId'});
 models.Products.belongsToMany(models.Store, {through: 'StoreProducts', foreignKey: 'productId'});

I want to "add" the following json object.

 var store = {
   name:'corner store',
   address: '123 Main Street',
   products: [
     'string beans', 'coffee', 'milk'
   ]
 };

Looking for any direction, I've tried about 10 routes and the best I was able to get was the Store and Product records created, but nothing relational.

1

There are 1 best solutions below

3
On BEST ANSWER

Have a look at nested creation (the feature is not documented yet)

Store.create({
  name:'corner store',
  address: '123 Main Street',
  products: [
    { name: 'string beans' }, { name: 'coffee' }, { name: 'milk' }
  ]
}, {
  include: [Product]
});

This will create both stores and products and associate the two.

Note, that this only works for creation - you cannot use it to associate new products with an already existing store etc.

Store.find().then(function (store) {
  store.createProduct({ name: 'hats' });
});