我的模特:

'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

我究竟做错了什么?

最佳答案

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

正确的解决方案是在create模型上调用Entity,将UserId字段设置为dbUser.id。因此,类似:

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


(您可能不得不大写)。

另外,我认为您可能想要User.hasMany(models.Entity),但这只是让我措手不及。

07-28 09:11