繁体   English   中英

续集:addUser 不是 function

[英]Sequelize: addUser is not a function

我正在学习使用 Sequelize,我很困惑。 我有两个模型,用户和沙龙,它们之间具有 N:M 关系,由辅助表 UsersSalons 介导(因此,用户可能管理许多沙龙,例如特许经营,或者沙龙可能由许多员工管理)

创建新沙龙时,我的目的是将登录用户与其关联。 但是,当我将新沙龙保存在数据库中时,它永远不会与用户关联,并返回此错误:

ERROR PUT /salons Error: TypeError: salon.addUser is not a function

谷歌搜索时,这个错误的常见原因似乎是试图将 function 应用于整个 model class 而不是它的一个实例,但这不是它的实例。

这是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 模型,以及 UsersSalons 表是如何创建的:

'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路线和 output 的更新代码:

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的 model 相关的别名命名:

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并从then的处理程序创建salon实例。 应该是这样的:

.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)))

根据 Anatoly 的回答找到了解决方案,但更简单。 如果我们在req.user[0]中有用户的 ID,这足以将我们的新salon与它关联起来,我们不需要在我们的数据库中再次搜索该用户。

这将是最终的代码片段:

router.put('/', checkLoggedIn, (req, res, next) => {
  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) => {
      salon.addUser(req.user[0].id)
      return salon
    })
    .then((salon) => res.status(200).json(salon))
    .catch((err) => next(new Error(err)))
})

再次感谢阿纳托利的帮助。 这是无价的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM