Sequelize.js belongsToMany实例方法创建不起作用?

时间:2015-02-09 20:24:32

标签: javascript postgresql sequelize.js

我的模特:

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Entity;
  return Entity = sequelize.define('Entity', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    classMethods: {
      associate: function(models) {
        return Entity.belongsToMany(models.User);
      }
    }
  });
};

'use strict';
module.exports = function(sequelize, DataTypes) {
  var User;
  return User = sequelize.define('User', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isEmail: true
      }
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false
    },
    status: {
      type: DataTypes.ENUM('active', 'inactive'),
      defaultValue: 'active'
    }
  }, {
    instanceMethods: {
      display: function() {
        var user;
        user = {
          name: this.name,
          email: this.email,
          username: this.username,
          active: this.active
        };
        return user;
      }
    }
  }, {
    classMethods: {
      associate: function(models) {
        return User.belongsToMany(models.Entity);
      }
    }
  });
};

我想创建一个用户,然后将一个实体附加到该用户,所以我正在做:

newUser = {
  name: req.body.name,
  email: req.body.email,
  username: req.body.username,
  password: req.body.password
};

global.db.User.create(newUser).then(function(dbUser) {
  var newEntity;
  newEntity = {
    name: newUser.name + " Default Entity"
  };
  console.log(dbUser);
  return dbUser.createEntity(newEntity);
}).then(function(dbEntity) {
  return console.log(dbEntity);
});

但我收到错误:[TypeError: Object [object SequelizeInstance] has no method 'createEntity']

这是使用Sequelize v2.0.0-rc8

我做错了什么?

1 个答案:

答案 0 :(得分:2)

dbUser是一个实例,因此dbUser.createEntity()正在调用createEntity()实例上的实例方法dbUser。哪个不存在。

正确的解决方案是在create模型上调用EntityUserId字段设置为dbUser.id。所以,像:

global.db.Entity.create({name: 'blah blah blah', UserId: dbUser.id})

(你可能不得不弄乱大写)。

另外,我想你可能想要User.hasMany(models.Entity),但那只是让我措手不及的事。