Jim Jin
Jim Jin

Reputation: 1509

Destructuring of the object returned by mongodb query result

Let's say we start a mongodb query statement as the following:

const user = await db.users.findOne(...);
console.log(user);

The result is good.

{
  _id: 5f60647c28b90939d0e5fb24,
  tenantId: '5e6f7c86e7158b42bf500371',
  username: 'aaaa',
  email: '[email protected]',
  createdAt: 2020-09-15T06:51:40.531Z,
  updatedAt: 2020-09-15T06:51:40.531Z,
  __v: 0
}

Then we use destructuring.

const { _id, username, ...others } = user;
console.log(others);

We get a weird thing:

[
  [
    '$__',
    InternalCache {
      strictMode: false,
      selected: [Object],
      shardval: undefined,
      saveError: undefined,
      validationError: undefined,
      adhocPaths: undefined,
      removing: undefined,
      inserting: undefined,
      saving: undefined,
      version: undefined,
      getters: {},
      _id: 5f60647c28b90939d0e5fb24,
      populate: undefined,
      populated: undefined,
      wasPopulated: false,
      scope: undefined,
      activePaths: [StateMachine],
      pathsToScopes: {},
      cachedRequired: {},
      session: undefined,
      '$setCalled': Set(0) {},
      ownerDocument: undefined,
      fullPath: undefined,
      emitter: [EventEmitter],
      '$options': [Object]
    }
  ],
  [ 'isNew', false ],
  [ 'errors', undefined ],
  [ '$locals', {} ],
  [ '$op', null ],
  [
    '_doc',
    {
      _id: 5f60647c28b90939d0e5fb24,
      tenantId: '5e6f7c86e7158b42bf500371',
      username: 'aaaa',
      email: '[email protected]',
      createdAt: 2020-09-15T06:51:40.531Z,
      updatedAt: 2020-09-15T06:51:40.531Z,
      __v: 0
    }
  ],
  [ '$init', true ]
]

What's going on here? And how to make destructuring work again? There is the same error on Object.entries(others). There is one workaround, I can stringify it and then parse it back. But this is obviously redundant.

Upvotes: 11

Views: 6255

Answers (2)

kPrananda
kPrananda

Reputation: 205

this works for me :


const user = UserModel.findOne({...});
const { _id, username, ...others } = user.toObject();


Upvotes: 8

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

By default, Mongoose queries return an instance of the Mongoose Document class. That's why you get the weird result after destructuring. In your case, you should use .lean() on your query to get expected result;

Upvotes: 15

Related Questions