0

I'm not really good at English and coding something. My OS is Mac and here is my basic info dialect : mysql sequelize-ver: 6.3.3 folder structure

I wrote my problem in the below on my question. First, I imported .sql file to my database and i made models automatically from sequelize-auto, and also migrated automatically from sequelize-auto-migrate. ( I really appreciate about it. )

Here is my Mentors model ( I made signUp controller from this model. )

/* jshint indent: 2 */
// eslint-disable-next-line no-unused-vars
const { Model } = require('sequelize');

module.exports = function (sequelize, DataTypes) {
  return sequelize.define('Mentors', {
    id: {
      autoIncrement: true,
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
    },
    mentor_name: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    nickname: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    email: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    password: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    sex: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    phone: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    birthday: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    certification_path: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    intro: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: true,
    },
  }, {
    sequelize,
    tableName: 'Mentors',
  });
};

and here is my model index.js

/* eslint-disable global-require */
/* eslint-disable import/no-dynamic-require */
// 'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');

const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development'; // 환경변수 NODE_ENV를 설정 안 해줄 경우 test 객체 연결 정보로 DB 연결 설정
const config = require(__dirname, +'/../config/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) => ((file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')))
  .forEach((file) => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    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;

and last, here is my signUp controller

const { Mentors } = require('../../models/Mentors');

module.exports = {
    post: (req, res) => {
        const {
 // eslint-disable-next-line camelcase
 mentor_name, nickname, email, password, sex, phone, birthday, certification_path, intro,
} = req.body;

        Mentors
        .findOrCreate({
            where: {
                email,
            },
            defaults: {
                mentor_name,
                nickname,
                password,
                sex,
                phone,
                birthday,
                certification_path,
                intro,
            },
        })
        // eslint-disable-next-line consistent-return
        .then(async ([result, created]) => {
            if (!created) {
                return res.status(409).send('Already exists user');
            }
            const data = await result.get({ plain: true });
            res.status(200).json(data);
        }).catch((err) => {
            res.status(500).send(err);
        });
        // console.log('/mentor/signup');
    },
};

and now, I'm facing this error when I type 'npm start'

TypeError: Cannot read property 'findOrCreate' of undefined

error screenshot

I googled a lot because of this problem, but still can't find out solution... please help me how to solve this problem.

here is my config.js

development: { // 배포할 때 RDS 연결 정보
            username: 'root',
            password: '(something)',
            database: 'user',
            host: 'localhost',
            port: 3001,
            dialect: 'mysql',
            logging: false,
    },
};

here is my app.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
const port = 3001;

// routes
const mentorRouter = require('./routes/mentor');
// const menteeRouter = require('./routes/mentee');

/*
 * bodyparser.json() - body로 넘어온 데이터를 JSON 객체로 변환
 */
app.use(bodyParser.json());
/*
 * bodyParser.urlencoded({ extended }) - 중첩 객체를 허용할지 말지를 결정하는 옵션
 * 참고 링크(https://stackoverflow.com/questions/29960764/what-does-extended-mean-in-express-4-0/45690436#45690436)
 */
app.use(bodyParser.urlencoded({ extended: false }));
/*
 * cors() - CORS를 대응하기 위한 라이브러리 ( Access-Control-Allow-Origin: * )
 * https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
 */
app.use(
  cors({
    origin: ['http://localhost:3000'],
    methods: ['GET', 'POST', 'PATCH'],
    credentials: true,
  }),
);

app.use('/mentor', mentorRouter);
// app.use('/mentee', menteeRouter);

app.set('port', port);
app.listen(app.get('port'), () => {
  console.log(`app is listening in PORT ${app.get('port')}`);
});

// 나중 테스트 코드에서 쓰기 위해 export
module.exports = app;
Rohit Ambre
  • 921
  • 1
  • 11
  • 25
FreshMan2
  • 19
  • 6

1 Answers1

0

change your import statement in controller to import model index file like this

const db = require('../../models');

and then use it like

db.Mentors.findOrCreate()

Rohit Ambre
  • 921
  • 1
  • 11
  • 25
  • Thank you for answering my question! I did it and there's another error came out. TypeError: Cannot read property 'use_env_variable' of undefined – FreshMan2 Jul 21 '20 at 12:30
  • ohk that's weird, the changes I requested should not cause that error....are you setting your env variable manually? is it set on `development` – Rohit Ambre Jul 21 '20 at 12:35
  • I add my config.js. umm.. maybe I did wrong..(?) I'm sorry, I don't really know what is correct env setting – FreshMan2 Jul 21 '20 at 12:43
  • your config file looks ok, if ur running mysql on 3001 port....I was asking about `NODE_ENV` variable...how you are starting your app? – Rohit Ambre Jul 21 '20 at 12:46
  • I start my app from app.js, i'll add my app.js too. Thanks a lot for helping me! – FreshMan2 Jul 21 '20 at 12:48
  • check if the `config.js` file where DB config is set that location is correct in your `/model/index.js` file. on line no. 10 – Rohit Ambre Jul 21 '20 at 12:57
  • and also check if you remove the changes I requested in this answer, then whether it is working fine...... if then also it is giving error then something else is causing this new issue – Rohit Ambre Jul 21 '20 at 12:59
  • Thanks for answering my awful question, i'll try it after dinner! i can't upvote your answer bcs my reputation is below 15...lol – FreshMan2 Jul 21 '20 at 13:06