Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript Mongoose虚拟id字段和JSON响应_Typescript_Mongoose_Nestjs - Fatal编程技术网

Typescript Mongoose虚拟id字段和JSON响应

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

我正在使用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.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?