Sequelize Associate Objects fails with has no method addX

Sequelize Associate Objects fails with has no method addX

Problem

Trying to associate a phone number with a user is resulting in node telling me that the User object has no method addPhonenumber. (also happens with setPhonenumber)

req.user.setPhonenumbers(phonenumber).success(function(user){
             ^
TypeError: Object [object Object] has no method 'setPhonenumbers'

How do I properly associate objects? Code below.

Object definitions in models.js:

exports.User = require("./user")(sequelize, Sequelize);
exports.Phonenumber = require("./phonenumber")(sequelize, Sequelize);
exports.Recording = require("./recording")(sequelize, Sequelize);
exports.Call = require("./call")(sequelize, Sequelize);

User
  .hasMany(Phonenumber)
  .hasMany(Recording);

Phonenumber
  .belongsTo(User)
  .hasOne(Recording)
  .hasMany(Call);

Recording.belongsTo(User);

Call.belongsTo(Phonenumber);

Trying to set association:

      var phonenumber = yp.db.Phonenumber.create({
        number: number.phone_number
      }).success(function(number){
        console.log(number);
        console.log(req.user);
        req.user.setPhonenumbers(phonenumber).success(function(user){
          console.log(user);
        });
      });

And the console.log result of the above referenced req.user:

{ __options: 
   { timestamps: true,
     instanceMethods: { fullname: [Function] },
     classMethods: {},
     validate: {},
     freezeTableName: false,
     underscored: false,
     syncOnAssociation: true,
     paranoid: true,
     omitNull: false,
     hasPrimaryKeys: false },
  hasPrimaryKeys: false,
  selectedValues: 
   { firstname: 'Nathan',
     lastname: 'Loyer',
     email: 'xxx@gmail.com',
     password: '****',
     facebookid: '****',
     id: 2,
     createdAt: Thu Feb 28 2013 20:40:29 GMT-0600 (CST),
     updatedAt: Wed Mar 06 2013 20:22:05 GMT-0600 (CST),
     deletedAt: null },
  firstname: 'Nathan',
  lastname: 'Loyer',
  email: 'xxx@gmail.com',
  password: '****',
  facebookid: '****',
  id: 2,
  createdAt: Thu Feb 28 2013 20:40:29 GMT-0600 (CST),
  updatedAt: Wed Mar 06 2013 20:22:05 GMT-0600 (CST),
  deletedAt: null,
  isNewRecord: false }

What am I missing?

Thanks!

Problem courtesy of: Nathan Loyer

Solution

Each of your hasMany needs a matching belongsTo. And, the associated function will be setPhonenumbers. See: http://www.sequelizejs.com/documentation#associations-associating-objects

Solution courtesy of: dankohn

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *