Typescript Mongoose虚拟id字段和JSON响应
我正在使用NestJS和Mongoose。我只是从mongo数据库返回文档对象,如下所示:Typescript Mongoose虚拟id字段和JSON响应,typescript,mongoose,nestjs,Typescript,Mongoose,Nestjs,我正在使用NestJS和Mongoose。我只是从mongo数据库返回文档对象,如下所示: @Get() @UseGuards(AuthGuard('jwt')) async getCompany(@AuthUser() user: User) { const company = await this.companyModel.findById(user.companyId) this.logger.log(company) this.logger.log(company
@Get()
@UseGuards(AuthGuard('jwt'))
async getCompany(@AuthUser() user: User) {
const company = await this.companyModel.findById(user.companyId)
this.logger.log(company)
this.logger.log(company.id)
return company
}
由于Mongoose会自动在模型上创建一个id字段,因此我可以看到id字段的值。但响应json中不返回id字段。响应包括_id字段,而不是id
我应该怎么做才能将id字段返回到客户端而不是模式定义中的_id?执行以下操作:
export const MySchema = new mongoose.Schema({
field_name: String,
}, { _id: true,
collection: 'collection_name',
id: true, toJSON: {
virtuals: true,
versionKey: true
}
})
我刚刚进行了测试,它成功了。您能在问题中添加公司型号代码吗?如果_id中已经有相同的值,为什么还需要id?