我试图用nestjs在mongoose中获取一个记录列表,问题是当_id返回的记录是空对象时。下面是我的代码:
const filters: any = {};
if (typeof dto.searchTerm == 'string') {
filters['username'] = { $regex: dto.searchTerm, $options: 'i' };
}
if (Object.values(UserRole).includes(dto.filterByUserRole)) {
filters['role'] = dto.filterByUserRole;
}
const users = await this.userModel
.find(filters, 'username email role bio createdAt updatedAt image')
.limit(dto.size)
.skip(dto.offset)
.lean()
.exec();
const usersCount = await this.userModel.find(filters).count();
return { content: users as any, count: usersCount };
我希望返回的数据是这样的:
{
"content": [
{
"_id": "6416ea08b1019420467b3f20",
...the other field
},
],
"count": 1
}
但我得到了这样的回应
{
"content": [
{
"_id": {},
...the other data
},
"count": 1
}
如何解决此问题?
1条答案
按热度按时间b4lqfgs41#
我怀疑你的_id在Mongo中被存储为本地ObjectId。尝试访问Mongoose在模型上提供的“id”字符串字段,你需要删除.lean()的使用。这将取决于你使用的Mongo/Mongoose的版本,以及你的模式是如何设置的(例如,你可以关闭“id”)