简体   繁体   中英

Sequelize model association update not reflected as expected

I'm trying to associate tags to an organization via sequelize's set<Model>(...) method and it seems to be setting the tags correctly in the db but the updated org with these new tags does not reflect this.

organization model

'use strict';
module.exports = (sequelize, DataTypes) => {
  var organization = sequelize.define('organization', {
  ...
  }, {});
  organization.associate = function (models) {
    // associations can be defined here
    organization.hasMany(models.tag)
  };
  return organization;
};

tag model

'use strict';
module.exports = (sequelize, DataTypes) => {
  ...
  tags.associate = function(models) {
    // associations can be defined here
    tags.belongsTo(models.organization)
  };
  return tags;
};

method

/**
 * Update organization
 * @param {object} db     - The db handle
 * @param {object} stats  - The datadog client
 */
function updateOrganization(db, stats) {
  return function (req, res) {

    let tagsToAdd = []
    let tagsToDelete = []
    let myOrg

    db.organization.findOne({
      where: {
        id: req.params.id
      },
      include: ['tags', 'users', 'retrievals']
    })
      .then(org => {
        myOrg = org
        return org.getTags()
      })
      .then(tags => {
        let promises = []

        ...a bunch of irrelevant logic

        // Add all the new tags
        tagsToAdd.forEach(tag => {
          promises.push(myOrg.createTag({ name: 'newTag' }))
        })

        return Promise.all(promises)
      })
      .then(updatedOrg => {
        console.log('updatedOrg = ', updatedOrg) <-- Does NOT have tags in updated org output even though they actually exist in db. Why not???
        return res.status(HttpStatus.OK).send(updatedOrg)
      })
  }
}

After countless hours of smashing my skull against anything near me i finally figured out that i needed to call reload()

.then(updatedOrg => {
  console.log('updatedOrg = ', updatedOrg)
  return res.status(HttpStatus.OK).send(updatedOrg)
})

should be

.then(updatedOrg => {
  return myOrg.reload()
})
.then(updatedOrg => {
  return res.status(HttpStatus.OK).send(updatedOrg)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM