mongoose id와 _id 접근

고재개발·2021년 7월 27일
1

node 모듈 mongoose를 활용해서 데이터를 생성하면,
_id를 자동으로 생성해준다.

이 자동 생성된 _id에 접근할 때는 신기하게
._id와 .id로 모두 접근이 가능하다.

예를 들면 아래와 같다. 아래 data는 name, email 정보를 넣어 만든 것이다.

data = 
{
  _id: 60ff9826591d828bf80577dc,
  name: 'Gojae',
  email: 'gojae@gmail.com',
  __v: 0
}

여기 _id를 조회할 때는 .id_id 모두 가능하다.

console.log(data.id);
console.log(data._id);

결과값

>>> 60ff9826591d828bf80577dc
>>> 60ff9826591d828bf80577dc



+ 그러나 둘의 type은 다르다.

console.log(typeof(data.id));
console.log(typeof(data._id));

결과값

string
object

.id로 조회하면 string이 나오고, ._id로 조회하면 object가 반환된다.

profile
고재개발

0개의 댓글