gpt4 book ai didi

javascript - 无法使用 sequelize-auto 读取未定义的属性 'findOrCreate'

转载 作者:行者123 更新时间:2023-12-03 22:34:24 27 4
gpt4 key购买 nike

我不太擅长英语和编码。我的操作系统是 Mac,这是我的基本信息dialect : mysqlsequelize-ver: 6.3.3 folder structure
我在下面的问题中写了我的问题。
首先,我将 .sql 文件导入我的数据库,并从 sequelize-auto 自动制作模型,并从 sequelize-auto-migrate 自动迁移。 (我真的很感激。)
这是我的导师模型(我从这个模型制作了注册 Controller 。)

/* 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;
最后,这是我的注册 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');
},
};
现在,当我输入“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 }) - 중첩 객체를 허용할지 말지를 결정하는 옵션
* 참고 링크(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;

最佳答案

更改 Controller 中的导入语句以导入这样的模型索引文件const db = require('../../models');然后像这样使用它db.Mentors.findOrCreate()

关于javascript - 无法使用 sequelize-auto 读取未定义的属性 'findOrCreate',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63014304/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com