본문 바로가기
DataBase/mongoDB

mongoose) 결과값에 spread 연산자 사용 시

by 박채니 2024. 1. 15.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.
개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.

 

mongoose spread 연산자 사용 시

 

mongoose를 이용하여 MongoDB 작업을 수행 중, 기존 DB 데이터 + 추가 데이터를 전달해주기 위해 spread 연산자를 사용하여 response 전달을 해주려고 했습니다.

 

findById로 하나의 DB 데이터를 가져오려는 상황

const user = await User.findById(id);
console.log(user);

콘솔창
{
    "_id": "6580049055722ca0b247771f",
    "title": "test",
}

 

ex> "add_data"라는 데이터를 추가로 전달해줄 때

const user = await User.findById(id);
console.log({
    ...user,
    add_data: "추가된 데이터"
});

원하는 결과값
{
    "_id": "6580049055722ca0b247771f",
    "title": "test",
    "add_data": "추가된 데이터"
}

 

위와 같이 데이터를 추가하길 원했지만, 실제 결과값은 아래와 같았습니다.

 

실제 데이터

const user = await User.findById(id);
console.log({
    ...user,
    add_data: "추가된 데이터"
});

실제 결과값
{
  '$__': InternalCache {
    activePaths: StateMachine { paths: [Object], states: [Object] },
    skipId: true,
    selected: {
      _id: 1,
      title: 1,
    },
    exclude: false
  },
  '$isNew': false,
  _doc: {
    _id: new ObjectId('6580049055722ca0b247771f'),
    title: 'test',
  },
  add_data: 'add'
}

단순 DB 조회 데이터만을 가지고 있는 객체가 아닌, 확장된 mongoose 객체가 출력되는 것을 확인할 수 있습니다.

 

따라서, Mongoose의 Document.toObject() 함수를 통해 데이터베이스에서 가져온 일반 객체로 변환해주었습니다.

const user = await User.findById(id);
console.log({
    ...user.toObject(),
    add_data: "추가된 데이터"
});

콘솔창
{
    "_id": "6580049055722ca0b247771f",
    "title": "test",
    "add_data": "추가된 데이터"
}​

 

✅ 참고 사이트

https://stackoverflow.com/questions/48014504/es6-spread-operator-mongoose-result-copy

 

es6 spread operator - mongoose result copy

I'm developping an express js API with mongo DB and mongoose. I would like to create an object in Javascript es6 composed of few variables and the result of a mongoose request and want to do so wi...

stackoverflow.com