node.js - 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)
。有一种解决方法,我可以对其进行字符串化,然后将其解析回来。但这显然是多余的。
解决方案
默认情况下,Mongoose 查询返回Mongoose Document 类的实例。这就是为什么你在解构后得到奇怪的结果。在您的情况下,您应该在查询中使用.lean() 以获得预期结果;
推荐阅读
- unity3d - 需要帮助 Assets\FlyLittleBird.cs(7,27): error CS1003: Syntax error, ',' expected
- javascript - 使用 date-fns 将日期解析为 UTC 的正确方法
- rxjs - 以编程方式离开 rxjs-for-await 循环
- postgresql - WAL 文件 LSN 如何反映它们在抽象 WAL 序列中的位置
- html - 包含iframe的flexbox内奇怪的CSS宽度?
- python - 使用带有 debugpy 的 VS Code 无法连接到 AWS EC2 实例
- wix - Wix 工具集 - CustomAction - ExeCommand - 1 失败 1 成功。你能帮助理解为什么吗?
- git - 检查我是否有对 ssh-git 存储库的密钥驱动访问而不克隆它
- typescript - 如何将运行时字符串转换为字符串枚举
- python - 在 VS Code 中从 Python 调试 C++