假设我们开始一个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)上出现相同的错误。有一个解决办法,我可以把它串起来,然后再解析回来。但这显然是多余的。
发布于 2020-09-15 15:55:46
默认情况下,Mongoose查询返回Mongoose Document class的一个实例。这就是为什么你在解构之后会得到奇怪的结果。在您的例子中,您应该在查询中使用.lean()来获得预期的结果;
发布于 2021-05-28 22:08:22
当我使用mongoose时,这对我是有效的:
const user = UserModel.findOne({...});
const { _id, username, ...others } = user.toObject();https://stackoverflow.com/questions/63897396
复制相似问题