seanscal
seanscal

Reputation: 568

Using sequelize to make an API with hasMany relationship postgresql

I am using sequilize on top of node.js and express in order to create an API that my react can access using this tutorial http://mherman.org/blog/2015/10/22/node-postgres-sequelize/#.WSJ77BMrLBL. I cannot get the database to populate with an object called a store with products. What I have as of now is:

routes:

    // get all stores
router.get('/stores', function(req, res) {
  models.Store.findAll({}).then(function(stores) {
    res.json(stores);
  });
});

// get single store
router.get('/stores/:id', function(req, res) {
  models.Store.find({
    where: {
      id: req.params.id
    }
  }).then(function(store) {
    res.json(store.productId);
  });
});

// add new store
router.post('/stores', function(req, res) {
  models.Store.create({
    name: req.body.name,
    productId: req.body.product_id
  }).then(function(store) {
    res.json(store);
  });
});

store:

    'use strict';
module.exports = function(sequelize, DataTypes) {
  var Store = sequelize.define('Store', {
    name: {
      type: DataTypes.STRING,
      defaultValue: ""
    },
    description: {
      type: DataTypes.STRING,
      defaultValue: ""
    },
    phone: {
      type: DataTypes.STRING,
      defaultValue: ""
    },
    email: {
      type: DataTypes.STRING,
      defaultValue: ""
    },
    image_url: {
      type: DataTypes.STRING,
      defaultValue: ""
    },
  }, {
    classMethods:{
        associate:function(models){
            Store.hasMany(models.Product, { foreignKey: 'productId'} );
        }
    }
  });
  return Store;
}

but when i run curl --data "name=test&product_id=1" http://127.0.0.1:5000/stores

i get: {"description":"","phone":"","email":"","image_url":"","id":2,"name":"test","updatedAt":"2017-05-22T05:43:10.376Z","createdAt":"2017-05-22T05:43:10.376Z"} and when i navigate to the stores pages i get the same thing but cannot see the productIds

What am I doing wrong? Can someone please offer some guidance.

Thanks!

Upvotes: 1

Views: 498

Answers (1)

Cam Schmidt
Cam Schmidt

Reputation: 71

Sequelize won't eager load the Products unless you explicitly tell it to include the associated model. Add the following option to your models.Store.findById request.

const options = {
    include: [{
        model: models.Product
    }]
};

So it reads:

models.Store.findById(req.params.id, options).then( ...

your response will have a Products key which will be an array of the associated products.

Upvotes: 3

Related Questions