Sequelize关联不从index.js执行

时间:2017-07-13 11:46:56

标签: javascript node.js sequelize.js

我有两个型号,User和Connection。花了好几个小时试图找出为什么我不能进行查询,假设关联正在工作,直到我终于意识到模型/ index.js中的代码块(从第27行开始)应该执行每个模型'联合功能甚至没有解雇。 Else区块开火并记录" Flag 1"每次都到控制台。

我看过无数其他模型定义和index.js文件的例子,做了一些小的改动,看看是否有什么能解决这个问题,而且我没有运气。完全迷失了。我错过了什么吗?

user.js的



'use strict';

...

module.exports = function(sequelize, DataTypes) {
	var User = sequelize.define('User', {
		id: { 
			type: DataTypes.INTEGER, 
			autoIncrement: true, 
			allowNull: false, 
			primaryKey: true 
		},
		email: { 
			type: DataTypes.STRING, 
			unique: true, 
			allowNull: false,
			isEmail: true 
		},
		password: { 
			type: DataTypes.STRING 
		},
		name: { 
			type: DataTypes.STRING 
		},
		avatarUrl: { 
			type: DataTypes.STRING 
		},
		resetPasswordExpires: {
			type: DataTypes.DATE
		},
		resetPasswordToken: {
			type: DataTypes.STRING
		},
		createdAt: {
			type: DataTypes.DATE
		},
		updatedAt: {
			type: DataTypes.DATE
		}
	}, {
		tableName: 'users',
		instanceMethods: instanceMethods,
		classMethods: {
			associate: function(models) {
				User.hasMany(models.Connection);
			},
			encryptPassword: function(password, cb) {
			...
			},
			findUser: function(email, password, cb) {
			...
			}
		},
		hooks: {
		...
		},
		indexes: [
		...
		]
	});
	
	return User;
};
};




connection.js



'use strict';

module.exports = function(sequelize, DataTypes) {
  var Connection = sequelize.define('Connection', {
    status: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    }
  }, {
    classMethods: {
      associate: function(models) {
        Connection.belongsTo(models.User);
      }
    }
  });
  return Connection;
};




这是models / index.js



'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.json')[env];
var db        = {};

if (config.use_env_variable) {
	var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
	var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
	.readdirSync(__dirname)
	.filter(function(file) {
		return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
	})
	.forEach(function(file) {
		var model = sequelize['import'](path.join(__dirname, file));
		db[model.name] = model;
	});

Object.keys(db).forEach(function(modelName) {
	if (db[modelName].associate) {
		console.log("Flag 0")
		db[modelName].associate(db);
	} else {
		console.log("Flag 1");
	}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;




1 个答案:

答案 0 :(得分:0)

开玩笑吧。想出来......

{{3}}

删除了classMethods和instanceMethods。