Radu Stoenescu
Radu Stoenescu

Reputation: 3205

Sequelize associations don't work, how to fix?

I've defined two models: User and Bookmark

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    name: DataTypes.STRING,
    email: DataTypes.STRING,
    pass: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    User.hasMany(models.Bookmark)
  };
  return User
};

'use strict'
module.exports = (sequelize, DataTypes) => {
  const Bookmark = sequelize.define('Bookmark', {
    title: DataTypes.STRING,
    url: DataTypes.STRING
  }, {})
  Bookmark.associate = function (models) {
    // Bookmark.belongsTo(models.User)
  }
  return Bookmark
}

The associate functions get called through the boilerplate code generated in models/index.js:

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})

However there are two things not happening that I expect they should:

User.findAll()
  .then(users => console.log(typeof users[0].getBookmarks))

Above getBookmarks is undefined.

And secondly, I see no schema updates being propagated to the data base.

I also tried reactivating // Bookmark.belongsTo(models.User) from the Bookmark model and nothing changes.

The problem and the fix

It turns out you have to explicitly call sync on an Sequelize instance, and, if the tables in the association are already present, you have to include the argument {force: true} for the association to be persisted to the database.

Upvotes: 0

Views: 1343

Answers (1)

Ratul Sharker
Ratul Sharker

Reputation: 8013

To get the associated Bookmarks you missed to include Bookmark while querying for User.

Including Bookmark the query should look like following

User.findAll({
    include: [
        {
            model: Bookmark
        }      
    ]
}).then( users => {
    // you now get the `users`, with `bookmarks` associated with it.
});

Upvotes: 1

Related Questions