无法使用 sequelize-auto 读取未定义的 属性 'findOrCreate'
Cannot read property 'findOrCreate' of undefined with sequelize-auto
我不太擅长英语和编码。我的 OS 是 Mac 这是我的基本信息
dialect : mysql
sequelize-ver: 6.3.3
folder structure
我在下面写下了我的问题。
首先,我将 .sql
文件导入到我的数据库中,并从 sequelize-auto
自动制作模型,并从 sequelize-auto-migrate
自动迁移。 (我真的很感激。)
这是我的 Mentors 模型(我用这个模型制作了 signUp 控制器。)
/* 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',
});
};
这是我的模型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;
最后,这是我的注册控制器
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');
},
};
现在,我在键入 'npm start'
时遇到此错误
TypeError: Cannot read property 'findOrCreate' of undefined
error screenshot
因为这个问题我搜索了很多,但仍然找不到解决方案...
请帮我解决这个问题。
这是我的 config.js
development: { // 배포할 때 RDS 연결 정보
username: 'root',
password: '(something)',
database: 'user',
host: 'localhost',
port: 3001,
dialect: 'mysql',
logging: false,
},
};
这是我的 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 }) - 중첩 객체를 허용할지 말지를 결정하는 옵션
* 참고 링크(
*/
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;
更改控制器中的导入语句以像这样导入模型索引文件
const db = require('../../models');
然后像
一样使用它
db.Mentors.findOrCreate()
我不太擅长英语和编码。我的 OS 是 Mac 这是我的基本信息
dialect : mysql
sequelize-ver: 6.3.3
folder structure
我在下面写下了我的问题。
首先,我将 .sql
文件导入到我的数据库中,并从 sequelize-auto
自动制作模型,并从 sequelize-auto-migrate
自动迁移。 (我真的很感激。)
这是我的 Mentors 模型(我用这个模型制作了 signUp 控制器。)
/* 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',
});
};
这是我的模型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;
最后,这是我的注册控制器
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');
},
};
现在,我在键入 'npm start'
时遇到此错误TypeError: Cannot read property 'findOrCreate' of undefined
error screenshot
因为这个问题我搜索了很多,但仍然找不到解决方案... 请帮我解决这个问题。
这是我的 config.js
development: { // 배포할 때 RDS 연결 정보
username: 'root',
password: '(something)',
database: 'user',
host: 'localhost',
port: 3001,
dialect: 'mysql',
logging: false,
},
};
这是我的 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 }) - 중첩 객체를 허용할지 말지를 결정하는 옵션
* 참고 링크(
*/
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;
更改控制器中的导入语句以像这样导入模型索引文件
const db = require('../../models');
然后像
一样使用它db.Mentors.findOrCreate()