首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Sequelize: addUser不是函数

Sequelize: addUser不是函数
EN

Stack Overflow用户
提问于 2020-11-27 18:20:22
回答 2查看 388关注 0票数 2

我正在学习使用Sequelize,但我被难住了。我有两个模型,User和Salon,它们之间存在N:M关系,由辅助表UsersSalons进行协调(例如,一个用户可能管理多个沙龙,例如一个特许经营,或者一个沙龙可能由许多员工管理)。

创建新沙龙时,我的目的是将登录的用户与其关联。然而,虽然我可以将新的沙龙保存在数据库中,但它从未与用户关联,并返回以下错误:

代码语言:javascript
复制
ERROR PUT /salons Error: TypeError: salon.addUser is not a function

在Googling上搜索时,似乎此错误的常见原因是试图将函数应用于整个模型类,而不是它的一个实例,但这并不是这里发生的情况。

下面是PUT /salons路由:

代码语言:javascript
复制
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)))
})

以防万一,下面是用户和沙龙模型,以及UsersSalons表是如何创建的:

代码语言:javascript
复制
'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
}
代码语言:javascript
复制
'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
}
代码语言:javascript
复制
'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路由和输出的更新代码:

代码语言:javascript
复制
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)))
})
代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2020-11-28 02:31:13

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

代码语言:javascript
复制
Salon.belongsToMany(models.User, {
        through: 'UsersSalons',
        as: 'user',
        foreignKey: 'salonId',
        otherKey: 'userId',
      })
User.belongsToMany(models.Salon, {
        through: 'UsersSalons',
        as: 'salon',
        foreignKey: 'userId',
        otherKey: 'salonId',
      })

您也没有从then处理程序返回found user和created salon实例。应该是这样的:

代码语言:javascript
复制
.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)))
票数 1
EN

Stack Overflow用户

发布于 2020-12-01 03:28:52

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

这将是最终的代码片段:

代码语言:javascript
复制
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)))
})

再次感谢你,阿纳托利,你的帮助。它是无价的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65035612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档