0

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 Answer 1

4

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' });
});
Sign up to request clarification or add additional context in comments.

3 Comments

doesn't products needs to be Products ?
In this case yes - I'm just used to naming my models lower-cased :)
Thanks for the reply, going to give it a try.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.