2

There I have res is original object

{
  time: 2020-07-26T10:39:38.135Z,
  isTransfered: true,
  _id: 5f1d5d6b60755e75b48770a6,
  receiverAccountNumber: '12345678',
  transfererAccountNumber: '11111111',
  receiverName: 'Lê Công Tuyền',
  transfererName: 'Nguyễn Thanh Tuấn',
  amount: 1000000,
  content: "test chuyefo'seajfg",
  payFeeBy: 'transferer',
  type: { name: 'internal', bankCode: 'TUB' },
  __v: 0
}

And I got this result (called res2) is returned object using spread operator res2 = {...res} :

{
  '$__': InternalCache {
    strictMode: true,
    selected: {},
    // alot of key-value
    '$setCalled': Set(0) {},
    ownerDocument: undefined,
    fullPath: undefined,
    emitter: EventEmitter {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: 0,
      [Symbol(kCapture)]: false
    },
    '$options': { skipId: true, isNew: false, willInit: true }
  },
  isNew: false,
  errors: undefined,
  _doc: {
    time: 2020-07-26T10:39:38.135Z,
    isTransfered: true,
    _id: 5f1d5d6b60755e75b48770a6,
    receiverAccountNumber: '12345678',
    transfererAccountNumber: '11111111',
    receiverName: 'Lê Công Tuyền',
    transfererName: 'Nguyễn Thanh Tuấn',
    amount: 1000000,
    content: "test chuyefo'seajfg",
    payFeeBy: 'transferer',
    type: { name: 'internal', bankCode: 'TUB' },
    __v: 0
  },
  '$locals': {},
  '$op': null,
  '$init': true
}

I really dont know about this behavior of spread operator, that a lot of new key-value generated and the object I want to get is in _doc key.

Code is run on Nodejs v12 (nvm use 12)

Tuyen Le
  • 23
  • 3
  • if you want `res._doc` you dont need to use `...` – Lawrence Cherone Jul 26 '20 at 14:52
  • This has nothing to do with Express, but rather with mongoose. Your "original object" is not a plain object, but mondodb `Document` instance, and what it renders when you `console.log` it is not what the object actually consists of. Use `.toObject()`. – Bergi Jul 26 '20 at 14:54

1 Answers1

0

This is probably because the res here is a mongoose document which has these values.

When you are doing a mongoose query by default it returns a document object. In order to receive a plain object use lean(). If you use lean then you won't be getting these unnecessary data when using spread operator.

Schema.findOne(query).lean()

However, if you need a document object from mongoose then in this case you can try the following to get rid of other values you don't need.

 let res2 = { ...res.toObject() };
Deekshith Hegde
  • 1,318
  • 2
  • 15
  • 27