꾸준한프로그래밍

string을 mongoose ObjectId로 바꾸고 싶을때 본문

개발 오답노트

string을 mongoose ObjectId로 바꾸고 싶을때

꾸준이 2022. 1. 13. 01:31

 

간혹 mongoose에서 검색을 할때 파라미터로 받은 objectId가 type이 string이여서 제대로 조회가 안될때가 있다. 이럴때 string인 objectId의 type을 objectId의 type으로 변환해주는 작업이 필요하다. 그렇게 바꿔주기 위해선 mongoose.Types.ObjectId() 함수를 쓰면 된다.

const mongoose = require("mongoose");

let strObjectId = `61de84a38f86be68734b9cb7`;
// 16진수짜리 objectId(여기선 String)
let objectId = mongoose.Types.ObjectId(strObjectId);
// 16진수짜리 String을 ObjectId 타입으로 변환 

console.log(typeof strObjectId); // typeof는 뒤에있는 변수의 type을 알려주는 함수이다.
console.log(typeof objectId);
console.log(strObjectId);
console.log(objectId);

////////////// 결과값
string
object
61de84a38f86be68734b9cb7
new ObjectId("61de84a38f86be68734b9cb7")

// strObject의 type은 string이고, mongoose.Types.ObjectId(strObjectId)을 한 objectId의
// type은 object이다.
// 각각을 출력해보면 61de84a38f86be68734b9cb7와 new ObjectId("61de84a38f86be68734b9cb7")
// 로 각각 다르게 출력됨을 알 수 있다.

여기서 주의해야할점은, mongoose.Types.ObjectId() 함수를 쓰려고 할때, 반드시 안에 들어가는 변수는 16진수여야 한다는 것이다. 그렇지 않으면 오류가 발생함으로 주의할 필요가 있다.