解构mongodb查询结果返回的对象

Jim*_*Jin 4 mongoose mongodb node.js

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

const user = await db.users.findOne(...);
console.log(user);
Run Code Online (Sandbox Code Playgroud)

结果很好。

{
  _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
}
Run Code Online (Sandbox Code Playgroud)

然后我们使用解构。

const { _id, username, ...others } = user;
console.log(others);
Run Code Online (Sandbox Code Playgroud)

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

[
  [
    '$__',
    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 ]
]
Run Code Online (Sandbox Code Playgroud)

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

kPr*_*nda 7

这对我有用:


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


Run Code Online (Sandbox Code Playgroud)


Cuo*_*goc 5

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