본문 바로가기

카테고리 없음

[오류 해결] CastError: Cast to ObjectId failed for value "값" at path "_id" for model "모델명"

728x90
반응형

오류 문구

CastError: Cast to ObjectId failed for value "{ plan: '600be36d1f423d1e3c1356e9' }" at path "_id" for model "Feedback"
    at model.Query.exec (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\query.js:4358:21)
    at model.Query.Query.then (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\query.js:4450:15)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  messageFormat: undefined,
  stringValue: `"{ plan: '600be36d1f423d1e3c1356e9' }"`,
  kind: 'ObjectId',
  value: { plan: '600be36d1f423d1e3c1356e9' },
  path: '_id',
  reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
      at new ObjectID (C:\Users\MINJI\Desktop\greenday\node_modules\bson\lib\bson\objectid.js:59:11)
      at castObjectId (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\cast\objectid.js:25:12)
      at ObjectId.cast (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\schema\objectid.js:279:12)
      at ObjectId.SchemaType.applySetters (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\schematype.js:1110:12)
      at ObjectId.SchemaType._castForQuery (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\schematype.js:1545:15)
      at ObjectId.SchemaType.castForQuery (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\schematype.js:1535:15)
      at ObjectId.SchemaType.castForQueryWrapper (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\schematype.js:1512:20)
      at cast (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\cast.js:274:34)
      at model.Query.Query.cast (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\query.js:4759:12)
      at castQuery (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\query.js:4559:18)
      at model.Query.Query._findAndModify (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\query.js:3458:23)
      at model.Query.<anonymous> (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\query.js:3421:8)
      at model.Query._wrappedThunk [as _findOneAndRemove] (C:\Users\MINJI\Desktop\greenday\node_modules\mongoose\lib\helpers\query\wrapThunk.js:16:8)
      at C:\Users\MINJI\Desktop\greenday\node_modules\kareem\index.js:370:33
      at processTicksAndRejections (internal/process/task_queues.js:79:11)
}

상황

id를 받아와서 동일한 id를 가진 데이터를 검색하여 삭제하려고 했는데, 버튼을 눌러 동작하니 해당 오류가 발생했다.

해결

export const deleteFeedback = async (req, res) => {
	const {
		body: { id },
	} = req;
	try {
		await Feedback.findOneAndRemove({ plan: id });
	} catch (error) {
		console.log(error);
	}
	res.redirect(routes.plans);
};

위에서처럼 findOneAndRemove()를 사용해야 하는데 findByIdAndRemove()를 사용해서 그랬던 것으로, findOneAndRemove()로 수정하니 제대로 동작했다.

(코드 작성할 때 자동완성 되는 바람에 그런 것으로, 종종 동일한 실수로 오류가 발생했기 때문에 자동완성되는 코드도 유심히 보도록 노력해야 함)

728x90
반응형