首页 > 解决方案 > mongodb查询结果返回的对象的解构

问题描述

假设我们开始一个 mongodb 查询语句,如下所示:

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

结果很好。

{
  _id: 5f60647c28b90939d0e5fb24,
  tenantId: '5e6f7c86e7158b42bf500371',
  username: 'aaaa',
  email: 'xxxx@yy.com',
  createdAt: 2020-09-15T06:51:40.531Z,
  updatedAt: 2020-09-15T06:51:40.531Z,
  __v: 0
}

然后我们使用解构。

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

我们得到一个奇怪的东西:

[
  [
    '$__',
    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: 'xxxx@yyy.com',
      createdAt: 2020-09-15T06:51:40.531Z,
      updatedAt: 2020-09-15T06:51:40.531Z,
      __v: 0
    }
  ],
  [ '$init', true ]
]

这里发生了什么?以及如何让解构再次发挥作用?上也有同样的错误Object.entries(others)。有一种解决方法,我可以对其进行字符串化,然后将其解析回来。但这显然是多余的。

标签: node.jsmongodbmongoose

解决方案


默认情况下,Mongoose 查询返回Mongoose Document 类的实例。这就是为什么你在解构后得到奇怪的结果。在您的情况下,您应该在查询中使用.lean() 以获得预期结果;


推荐阅读