Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize association key is uppercased in response

Tags:

sequelize.js

How can I make Music to be `music?

{
  id: 4
  name: "playlist 1"
  created_at: "2015-04-21T21:43:07.000Z"
  updated_at: "2015-04-23T20:44:50.000Z"
  Music: [
    {
      id: 12
      name: "Deorro - Five Hours (Static Video) [LE7ELS]"
      video_id: "K_yBUfMGvzc"
      thumbnail: "https://i.ytimg.com/vi/K_yBUfMGvzc/default.jpg"
      created_at: "2015-04-22T21:46:21.000Z"
      updated_at: "2015-04-22T21:46:21.000Z"
      playlist_id: 4
    }
  ]
}

My query looks something like:

.get(function (req, res) {
    db.Playlist.findAll({
      include: [db.Music]
    }).then(function (playlists) {
      if(!playlists) {
        res.status(404).json({message: 'No playlist found!'});
        return;
      }

      res.json(playlists)
    })
  })

Playlist model:

module.exports = function(sequelize, DataType) {
  var Playlist = sequelize.define('Playlist', {
    name: DataType.STRING
  }, {
    classMethods: {
      associate: function(models) {
        Playlist.hasMany(models.Music, { foreignKey: 'playlist_id' });
      }
    },
    tableName:   'playlists',
    underscored: true
  });

  return Playlist;
};

Music model:

module.exports = function(sequelize, DataType) {
  var Music = sequelize.define('Music', {
    name: DataType.STRING,
    video_id:  DataType.STRING,
    thumbnail:  DataType.STRING
  }, {
    classMethods: {
      associate: function(models) {
        Music.belongsTo(models.Playlist);
      }
    },
    tableName:   'musics',
    underscored: true
  });

  return Music;
}
like image 1000
aegyed Avatar asked Feb 11 '23 08:02

aegyed


1 Answers

Either change the casing in your model name:

sequelize.define('music', ...)

Or provide an as key in the association:

Playlist.hasMany(Music, { as: 'music' })
like image 190
Jan Aagaard Meier Avatar answered Feb 19 '23 06:02

Jan Aagaard Meier