TypeErro:无法读取未定义的属性“创建”

时间:2021-03-12 12:59:03

标签: javascript mysql node.js sequelize.js next.js

每当我尝试从注册表中注册用户时,我都会收到此错误。 我已经尝试了我在 "TypeError: Cannot read property 'create' of undefined" 处得到的解决方案。 这是我的模型目录中的 index.js


    const fs = require("fs");
    const path = require("path");
    const Sequelize = require("sequelize");
    const basename = path.basename(__filename);
    const env = process.env.NODE_ENV || "development";
    const config = require(__dirname + "/../config.js")[env];
    const db = {};
    
    let sequelize;
    if (config.use_env_variable) {
      sequelize = new Sequelize(process.env[config.use_env_variable], config);
    } else {
      sequelize = new Sequelize(
        config.database,
        config.username,
        config.password,
        config
      );
    }
    
    fs.readdirSync(__dirname)
      .filter((file) => {
        return (
          file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
        );
      })
      .forEach((file) => {
        const model = sequelize['import'](path.join(__dirname, file));
        db[model.name] = model;
      });
    
    Object.keys(db).forEach((modelName) => {
      if (db[modelName].associate) {
        db[modelName].associate(db);
      }
    });
    
    db.sequelize = sequelize;
    db.Sequelize = Sequelize;
    
    module.exports = db;

这是我的模型中的 user.js


    const { Model } = require("sequelize");
    module.exports = (sequelize, DataTypes) => {
      class User extends Model {
        /**
              msg:
         * 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) {
          // define association here
        }
      }
      User.init(
        {
          firstName: DataTypes.STRING,
          lastName: DataTypes.STRING,
          email: DataTypes.STRING,
          userRole: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
              isIn: {
                args: [["Enrollment Officer", "Supervisor", "Support Officer"]],
              },
            },
          },
        },
        {
          sequelize,
          modelName: "Users",
        }
      );
      return User;
    };

这是我的 userService.js 文件

    import database from "@models/index";

    const { User } = database;
    
    export default class UserService {
      static async createUser(user) {
        try {
          const newUser = await User.create(user);
          return newUser;
        } catch (error) {
          throw error;
        }
      }
    }

错误指向我的 userService 文件中附加到用户的 .create 属性。

0 个答案:

没有答案