gpt4 book ai didi

javascript - Sequelize : addUser is not a function

转载 作者:行者123 更新时间:2023-12-03 22:16:47 25 4
gpt4 key购买 nike

我正在学习使用 Sequelize,但我被难住了。我有两个模型,User 和 Salon,它们之间有 N:M 关系,由一个辅助表 UsersSalons 介导(因此用户可能管理许多沙龙,例如特许经营,或者沙龙可能由许多员工管理)
创建新沙龙时,我的目的是将登录用户与其关联。但是,当我将新沙龙保存在数据库中时,它永远不会与用户关联,并返回此错误:

ERROR PUT /salons Error: TypeError: salon.addUser is not a function
当谷歌搜索时,这个错误的常见原因似乎是试图将该函数应用于整个模型类而不是它的一个实例,但这不是这里发生的情况。
这是 PUT /salons路线:
router.put('/', checkLoggedIn, (req, res, next) => {
const user = User.findOne({ where: { id: req.user[0].id } })
.then(() =>
Salon.create({
name: req.body.name,
street: req.body.street,
number: req.body.number,
zipcode: req.body.zipcode,
town: req.body.town,
province: req.body.province,
addressComplements: req.body.addressComplements,
phoneNumber: req.body.phoneNumber,
})
)
.then((salon) => {
console.log(salon)
salon.addUser(user) //and here is where the error happens
})
.then((salon) => res.status(200).json(salon))
.catch((err) => next(new Error(err)))
})
以防万一,以下是 User 和 Salon 模型,以及 UsersSalon 表的创建方式:
'use strict'
const { Model } = require('sequelize')
module.exports = (sequelize, DataTypes) => {
class Salon extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
Salon.belongsToMany(models.User, {
through: 'UsersSalons',
as: 'salon',
foreignKey: 'salonId',
otherKey: 'userId',
})
}
}
Salon.init(
{
name: { type: DataTypes.STRING, allowNull: false, unique: true },
street: { type: DataTypes.STRING, allowNull: false },
number: { type: DataTypes.STRING, allowNull: false },
zipcode: { type: DataTypes.STRING, allowNull: false },
town: { type: DataTypes.STRING, allowNull: false },
province: { type: DataTypes.STRING, allowNull: false },
addressComplements: DataTypes.STRING,
phoneNumber: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
sequelize,
modelName: 'Salon',
}
)
return Salon
}
'use strict'
const { Model } = require('sequelize')

module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
User.belongsToMany(models.Salon, {
through: 'UsersSalons',
as: 'user',
foreignKey: 'userId',
otherKey: 'salonId',
})
}
}
User.init(
{
email: {
type: DataTypes.STRING,
validate: { isEmail: true },
allowNull: false,
unique: true,
},
firstName: { type: DataTypes.STRING, allowNull: false },
lastName: { type: DataTypes.STRING, allowNull: false },
isActive: { type: DataTypes.BOOLEAN, defaultValue: false },
password: { type: DataTypes.STRING },
confirmationCode: DataTypes.STRING,
},
{
sequelize,
modelName: 'User',
}
)
return User
}
'use strict'

module.exports = {
up: async (queryInterface, Sequelize) => {
return queryInterface.createTable('UsersSalons', {
createdAt: { allowNull: false, type: Sequelize.DATE },
updatedAt: { allowNull: false, type: Sequelize.DATE },
userId: { type: Sequelize.INTEGER, primaryKey: true },
salonId: { type: Sequelize.INTEGER, primaryKey: true },
})
},

down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('UsersSalons')
},
}
编辑:在尝试了 Anatoly 的建议之后,仍然存在错误。这是 PUT /salons 的更新代码路线和输出:
router.put('/', checkLoggedIn, (req, res, next) => {
const user = User.findOne({ where: { id: req.user[0].id } })
.then(() => {
return Salon.create({
name: req.body.name,
street: req.body.street,
number: req.body.number,
zipcode: req.body.zipcode,
town: req.body.town,
province: req.body.province,
addressComplements: req.body.addressComplements,
phoneNumber: req.body.phoneNumber,
})
})
.then((salon) => {
console.log(`salon output after creation: ${salon}`)
return salon.addUser(user)
})
.then((salon) => res.status(200).json(salon))
.catch((err) => next(new Error(err)))
})
Executing (default): SELECT "id", "email", "firstName", "lastName", "isActive", "password", "confirmationCode", "createdAt", "updatedAt" FROM "Users" AS "User" WHERE "User"."id" = 1;
Executing (default): SELECT "id", "email", "firstName", "lastName", "isActive", "password", "confirmationCode", "createdAt", "updatedAt" FROM "Users" AS "User" WHERE "User"."id" = 1;
Executing (default): INSERT INTO "Salons" ("id","name","street","number","zipcode","town","province","phoneNumber","createdAt","updatedAt") VALUES (DEFAULT,$1,$2,$3,$4,$5,$6,$7,$8,$9) RETURNING "id","name","street","number","zipcode","town","province","addressComplements","phoneNumber","createdAt","updatedAt";
salon output after creation: [object SequelizeInstance:Salon]
Executing (default): SELECT "createdAt", "updatedAt", "salonId", "userId" FROM "UsersSalons" AS "UsersSalons" WHERE "UsersSalons"."salonId" = 15 AND "UsersSalons"."userId" IN ('[object Promise]');
ERROR PUT /salons Error: SequelizeDatabaseError: invalid input syntax for integer: "[object Promise]"
at [project route]/routes/salons.routes.js:34:26
at processTicksAndRejections (internal/process/task_queues.js:93:5)
PUT /salons 500 860.025 ms - 39

最佳答案

您在 belongsToMany 中混淆了别名协会。您应该为与作为第一个参数传递给 belongsToMany 的模型相关的别名命名。 :

Salon.belongsToMany(models.User, {
through: 'UsersSalons',
as: 'user',
foreignKey: 'salonId',
otherKey: 'userId',
})
User.belongsToMany(models.Salon, {
through: 'UsersSalons',
as: 'salon',
foreignKey: 'userId',
otherKey: 'salonId',
})
还有你没回发现 user并创建 salon来自 then 的实例处理程序。应该是这样的:
.then((user) =>
return Salon.create({
name: req.body.name,
street: req.body.street,
number: req.body.number,
zipcode: req.body.zipcode,
town: req.body.town,
province: req.body.province,
addressComplements: req.body.addressComplements,
phoneNumber: req.body.phoneNumber,
}).then((salon) => {
console.log(salon)
salon.addUser(user.id)
return salon
})
)
.then((salon) => res.status(200).json(salon))
.catch((err) => next(new Error(err)))

关于javascript - Sequelize : addUser is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65035612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com