TypeError: Cannot read properties of undefined (reading 'findOne') 질문
2007
작성자 없음
안녕하세요 제로초님!
현재 백엔드 파트 게시물 좋아요 기능을 구현하다가 갑자기 회원가입과 로그인 기능에서 오류가 떠서 질문드립니다.
회원가입을 하게 되면,
TypeError: Cannot read properties of undefined (reading 'findOne')
라는 오류가 발생하면서 데이터베이스에 데이터가 전송되지 않고 있습니다.
제가 생각하기에는 User모델에 문제가 발생하여 데이터가 들어가지 않아 findOne이 에러가 뜨는 것 같은데,,,
문제가 된다고 생각하는 코드 올리겠습니다.
models/index.js
const Sequelize = require("sequelize");
const env = process.env.NODE_ENV || "development";
const config = require("../config/config")[env];
const db = {};
const sequelize = new Sequelize(
config.database,
config.username,
config.password,
config,
);
db.Comment = require("./comment")(sequelize, Sequelize);
db.Hashtag = require("./hashtag")(sequelize, Sequelize);
db.Post = require("./post")(sequelize, Sequelize);
db.User = require("./user")(sequelize, Sequelize);
db.Image = require("./image")(sequelize, Sequelize);
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
}); // 반복문을 이용하여 각 데이터베이스의 관계를 설정해줌.
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
models/user.js
const DataTypes = require("sequelize");
const { Model } = DataTypes;
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"User", // id가 기본적으로 들어가있기 때문에 만들지 않아도 됨.
{
email: {
type: DataTypes.STRING(30),
allowNull: false, //필수
unique: true, //고유한 값
},
nickname: {
type: DataTypes.STRING(30),
allowNull: false, //필수},
},
password: {
type: DataTypes.STRING(100),
allowNull: false, //필수},
},
},
{
charset: "utf8",
collate: "utf8_general_ci", // 한글 저장
},
);
User.associate = (db) => {
db.User.hasMany(db.Post);
db.User.hasMany(db.Comment);
db.User.belongsToMany(db.Post, { through: "Like", as: "Liked" });
db.User.belongsToMany(db.User, {
through: "Follow",
as: "Followers",
foreignKey: "FollowingId",
});
db.User.belongsToMany(db.User, {
through: "Follow",
as: "Followings",
foreignKey: "FollowerId",
});
};
return User;
};
routes/user.js
const express = require("express");
const bcrypt = require("bcrypt");
const passport = require("passport");
const { User, Post } = require("../models");
const { isLoggedIn, isNotLoggedIn } = require("./middlewares");
const router = express.Router();
router.get("/", async (req, res, next) => {
// GET /user
try {
if (req.user) {
const fullUserWithoutPassword = await User.findOne({
where: { id: req.user.id },
attributes: {
exclude: ["password"],
},
include: [
{
model: Post,
attributes: ["id"],
},
{
model: User,
as: "Followings",
attributes: ["id"],
},
{
model: User,
as: "Followers",
attributes: ["id"],
},
],
});
res.status(200).json(fullUserWithoutPassword);
} else {
res.status(200).json(null);
}
} catch (error) {
console.error(error);
next(error);
}
});
router.post("/login", isNotLoggedIn, (req, res, next) => {
passport.authenticate("local", (err, user, info) => {
if (err) {
console.error(err);
return next(err);
}
if (info) {
return res.status(401).send(info.reason);
}
return req.login(user, async (loginErr) => {
if (loginErr) {
console.error(loginErr);
return next(loginErr);
}
const fullUserWithoutPassword = await User.findOne({
where: { id: user.id },
attributes: {
exclude: ["password"],
},
include: [
{
model: Post,
attributes: ["id"],
},
{
model: User,
as: "Followings",
attributes: ["id"],
},
{
model: User,
as: "Followers",
attributes: ["id"],
},
],
});
return res.status(200).json(fullUserWithoutPassword);
});
})(req, res, next);
});
router.post("/", isNotLoggedIn, async (req, res, next) => {
// async await을 이용하여 비동기 문제 해결
try {
const exUser = await User.findOne({
where: {
email: req.body.email,
},
}); // 같은 이메일을 사용하고 있는 사람이 있는지
if (exUser) {
return res.status(403).send("이미 사용중인 아이디입니다.");
} // return이 없으면 아래있는 res도 실행이 됨.
const hashedPassword = await bcrypt.hash(req.body.password, 13);
await User.create({
email: req.body.email,
nickname: req.body.nickname,
password: hashedPassword,
});
res.send("ok");
} catch (error) {
console.error(error);
next(error);
}
}); //post /user/
router.post("/user/logout", isLoggedIn, (req, res, next) => {
req.logout();
req.session.destroy();
res.send("ok");
});
module.exports = router;
오류 사진






답변 2
0
User가 undefined인게 에러의 원인이 맞기는 한데 올려주신 소스코드에 문제는 없어보입니다. 혹시 소스코드 저장하셨나요? console.log('User', User); 해보시면 undefined 나오면 모델쪽에 문제가 있습니다.
0
db.User = require("./user")(sequelize, Sequelize);
console.log('db.User', db.User);
하면 뭐가 나오나요? 여기가 undefined면 { User } = require('../models')로 import해도 undefined가 됩니다.
0

db연결성공
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
db.User User
{
Comment: Comment,
Hashtag: Hashtag,
Post: Post,
User: User,
Image: Image,
sequelize: <ref *1> Sequelize {
options: {
dialect: 'mysql',
dialectModule: null,
dialectModulePath: null,
host: '127.0.0.1',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone: '+00:00',
standardConformingStrings: true,
logging: [Function: log],
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: [Object],
transactionType: 'DEFERRED',
isolationLevel: null,
databaseVersion: 0,
typeValidation: false,
benchmark: false,
minifyAliases: false,
이렇게 뜹니다!
models/index.js 에서 콘솔 찍으면 되는게 맞는건가요?
0
const User = require('../models/user');
const Post = require('../models/post');
이렇게 했는데 똑같은 에러가 난다는 말씀이신가요??
넥스트 버젼 질문
0
91
2
로그인시 401 Unauthorized 오류가 뜹니다
0
104
1
무한 스크롤 중 스크롤 튐 현상
0
199
1
특정 페이지 접근을 막고 싶을 때
0
117
2
createGlobalStyle의 위치와 영향범위
0
104
2
인라인 스타일 리렌더링 관련
0
98
2
vsc 에서 npm init 설치시 오류
0
159
2
nextjs 15버전 사용 가능할까요?
0
166
1
화면 새로고침 문의
0
129
1
RTK에서 draft, state 차이가 있나요?
0
164
2
Next 14 사용해도 될까요?
0
455
1
next, node 버전 / 폴더 구조 질문 드립니다.
0
359
1
url 오류 질문있습니다
0
218
1
ssh xxxxx로 우분투에 들어가려니까 port 22: Connection timed out
0
393
1
sudo certbot --nginx 에러
0
1298
2
Minified React error 콘솔에러 (hydrate)
0
482
1
카카오 공유했을 때 이전에 작성했던 글이 나오는 버그
0
257
1
프론트서버 배포 후 EADDRINUSE에러 발생
0
341
1
npm run build 에러
0
526
1
front 서버 npm run build 중에 발생한 에러들
0
399
1
서버 실행하고 브라우저로 들어갔을때 404에러
0
351
2
css 서버사이드 랜더링이 적용되지 않아서 문의 드립니다.
0
291
1
팔로워 3명씩 불러오고 데이터 합쳐주는걸로 바꾸고 서버요청을 무한으로하고있습니다.
0
252
2
해시태그 검색에서 throttle에 관해 질문있습니다.
0
207
1





