์ค๋ฅ ๋ฐ์
Next.js ๊ฐ์๋ฅผ ๋ฃ๋ ๋์ค MongoDB์ ์ปฌ๋ ์ ์์ ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ค๋ ๊ณผ์ ์์ ๋ค์๊ณผ ๊ฐ์ ์ค๋ฅ๋ฅผ ๋ง์ฃผํ์ต๋๋ค.
TypeError: Class constructor ObjectId cannot be invoked without 'new'
![](https://blog.kakaocdn.net/dn/rm0HX/btr6Gp7J1Fg/nBDDniNJ8FGkf6Hgr6EDtK/img.png)
MongoDB์ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ ๋ ์์ฒด์ ์ผ๋ก ์ ์ฅ๋๋ _id ๊ฐ์ด ์๋๋ฐ, ์ด _id์ ํ์ ์ด ๋ฐ๋ก ObjectId์ ๋๋ค.
๊ฐ์ ์ฝ๋๋ผ ์์ธํ ์์ฑํ ์๋ ์์ง๋ง findOne() ๋ฉ์๋๋ฅผ ์ฌ์ฉํด _id ๊ฐ์ผ๋ก ํํฐ๋งํ ํ๋์ ๋ฌธ์๋ฅผ ๊ฐ์ ธ์ค๋ ค๋ ๋์ค ๋ฐ์ํ์ต๋๋ค.
์ฆ, string ํ์์ผ๋ก ๋์ด ์๋ id ๊ฐ์ ๋ด์ ๋ณ์ testId ๊ฐ ์์ ๋
findOne({
_id: ObjectId(testId)
});
์์ ๊ฐ์ด ์ฝ๋๋ฅผ ์์ฑํ์ด์. (์์๋ก ์ผ๋ถ๋ง ์์ฑ)
์ค๋ฅ ์ด์
ํด๋์ค ๋ชจ๋ธ์ new ํค์๋ ์์ด ์ฌ์ฉํ ์ ์๋๋ฐ, ObjectId๋ ํด๋์ค์์ต๋๋ค. (์ฐธ๊ณ ๋จ๋ฝ ๋งํฌ ์ฒซ๋ฒ์งธ)
๋ํ ์คํ์ค๋ฒํ๋ก์ฐ์์ ์ฐพ์๋ณด๋ babel์ด๋ typescript๋ฅผ ์ฐ๊ณ ์๋ค๋ฉด tsconfig.json ํ์ผ์์ ์ปดํ์ผ target์ ES6๋ก ์ค์ ํ๋ฉด ํด๊ฒฐ๋๋ค๊ณ ํฉ๋๋ค. ๊ทธ๋ฌ๋ ์ ๋ ๋๊ฐ์ง ๋ชจ๋ ์ฌ์ฉํ๊ณ ์์ง ์์์ ๋ค๋ฅธ ๋ฐฉ๋ฒ์ผ๋ก ํด๊ฒฐํ๊ฒ ๋์์ด์.
ํด๊ฒฐ ๋ฐฉ๋ฒ
findOne({
_id: new ObjectId(testId)
});
์ ๋ง ๋จ์ํ๊ฒ๋ ์์ new ํค์๋๋ฅผ ๋ถ์ฌ์ฃผ๊ธฐ๋ง ํ๋ฉด ํด๊ฒฐ๋์ต๋๋ค. ๐ ๊ฒ์ํ๋ ๋ค๋ฅธ ์ฌ๋ฌ ํด๊ฒฐ๋ฐฉ๋ฒ์ด ๋์ค๋๋ฐ ์ ๊ฐ ํด๊ฒฐํ ๋ฐฉ๋ฒ์ด ๋ง๋์ง๋ ๋ ์ฐพ์๋ด์ผํ ๊ฒ ๊ฐ๋ค์. ๊ธํ ๋ถ์ ๋ ์ ๋!
์ฐธ๊ณ
https://mongodb.github.io/node-mongodb-native/4.0/classes/objectid.html
ObjectId | mongodb
mongodb.github.io
Javascript ES6 TypeError: Class constructor Client cannot be invoked without 'new'
I have a class written in Javascript ES6. When I try to execute nodemon command I always see this error TypeError: Class constructor Client cannot be invoked without 'new' The full error is mentioned
stackoverflow.com