我一直在尝试从我的 Sequelize 数据库模型 Accounts 和 Dogs 中做一个 findall 路线:
db.Accounts.findAll({
where: {
admin:true,
},
include: [db.Dogs]
}).then((dbAdminAcc) => res.json(dbAdminAcc));
});
但是当我尝试运行应用程序和路由时,它不断返回:TypeError:无法读取未定义的属性“findAll”。
因此,在 index.js 中为模型文件夹做了一些控制台日志后,我发现所有模型在控制台中都显示为“模型是 [函数(匿名)]”,对于所有三个模型。这使我根本无法访问数据。
}).forEach((file) => {
console.log('The file is', file)
console.log(path.join(__dirname, file))
const model = require(path.join(__dirname, file));
console.log('Model is', model) // This is showing a function (anonymous instead of a name like Accounts)
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
console.log('DB with modelname:', (db[modelName]))
if(db[modelName].associate) {
db[modelName].associate(db);
}});
我查看了 Dogs 和 Accounts 模型中的语法是否正确,以查看是否缺少返回,但两个模型似乎都设置正确:
module.exports = (sequelize, DataTypes) => {
const Dogs = sequelize.define('Dogs', {
dog_name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [2,15],
},
},
breed: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [2,15],
},
},
age: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
len: [2,35],
},
isNumeric: true,
isInt: true,
},
food_requirements: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [2,200],
},
},
friendliness: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
len: [1,5],
},
isNumeric: true,
isInt: true,
},
});
Dogs.associate = (models) => {
// a Dogs must belong inside the Admin Account
// Dogs cannot be created without a petId (username)
Dogs.belongsTo(models.Accounts, {
foreignKey: {
allowNull: false,
},
});
};
return Dogs;
};
const bcrypt = require("bcryptjs");
module.exports = (sequelize, DataTypes) => {
const Accounts = sequelize.define('Accounts', {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isUserName: true
}
},
// The password cannot be null
password: {
type: DataTypes.STRING,
allowNull: false
},
//this true or false
admin: {
type: DataTypes.BOOLEAN,
defaultValue: false,
}
});
Accounts.associate = (models) => {
Accounts.hasMany(models.Dogs, {
onDelete: 'cascade'
});
};
Accounts.prototype.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
Accounts.addHook("beforeCreate", function(accounts) {
Accounts.password = bcrypt.hashSync(accounts.password, bcrypt.genSaltSync(10), null);
});
return Accounts;
};
我不知道接下来要尝试什么。有没有人知道为什么会发生这种情况以及如何解决它?任何帮助将不胜感激。谢谢
最佳答案
您应该使用 Sequelize import
函数注册模型,而不是仅仅使用 require
导入它们:
var model = sequelize['import'](path.join(models, file))
db[model.name] = model
UPD:自 v6 以来,此 import
方法已被弃用。使用@Abhishek 在他的评论中指出的方法。看看我的回答 here
关于sequelize.js - Sequelize 数据库模型作为(函数 [匿名])回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66413533/