Monday, 5 June 2017

Getting data populated from queries (with sequelize) in both ways?

I'm starting to work with sequelize (I'm pretty happy about it), but I still don't get how to work with field "population" (this term comes from mongo, I'm sorry :( )

Here's my model definition:

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    email: { type: Sequelize.STRING },
    firstName: { type: Sequelize.STRING },
    lastName: { type: Sequelize.STRING },
  }, {
    classMethods: {
      associate: function(models) {
        User.hasMany(models.Experience, {as: 'createdExperiences'})
      }
    }
  });

  User.sync({force: false}).then(() => {});

  return User;
};

and the other one:

module.exports = function(sequelize, DataTypes) {
  var Plan = sequelize.define('Plan', {
    title: { type: Sequelize.STRING },
  }, {
    classMethods: {
      associate: (models) => {

      }
    }
  });

  Plan.sync().then(function () {
    // Table created
  });

  return Plan;
};

I'm adding experiences like this:

UserInstance.addCreatedExperience(experience);

Which works great. I can get users and include the Plan like this:

User.findAll({include: [{model:Plan, as:'createdExperiences'}]}).then(function(users) {
});

then the users will have their Plans included in their objects.

The problem is that I cannot get working on the other way. If I get the experiences, how can I get the users to be populated on those objects?

Maybe it's a problem with the model definition.

Can anybody help me?

Thanks!



via Javier Manzano

No comments:

Post a Comment