๐Ÿ’ฟ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค

[MongoDB: ์˜ค๋ฅ˜] TypeError: Class constructor ObjectId cannot be invoked without 'new'

์˜ˆ์ง„-D 2023. 3. 29. 14:48
newMeetupId

์˜ค๋ฅ˜ ๋ฐœ์ƒ

Next.js ๊ฐ•์˜๋ฅผ ๋“ฃ๋˜ ๋„์ค‘ MongoDB์˜ ์ปฌ๋ ‰์…˜์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ค๋Š” ๊ณผ์ •์—์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์˜ค๋ฅ˜๋ฅผ ๋งˆ์ฃผํ–ˆ์Šต๋‹ˆ๋‹ค.

TypeError: Class constructor ObjectId cannot be invoked without 'new'
์˜ค๋ฅ˜ ํ™”๋ฉด
 

 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

https://stackoverflow.com/questions/51860043/javascript-es6-typeerror-class-constructor-client-cannot-be-invoked-without-ne

 

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