如何返回"id"而不是"_id"没有&;__v"到客户端使用express, mongoose和TypeScript?
我的代码如下:
界面
export default interface Domain {
name: string;
objects: DomainObject[]
}
创建接口
export default interface DomainCreate {
name: string
}
猫鼬模型
const DomainSchema = new Schema<Domain>({
name: { type: String, required: true },
});
const DomainModel = mongoose.model<Domain>("Domain", DomainSchema);
export { DomainModel, DomainSchema };
服务export default class DomainService {
public async create(params: DomainCreate): Promise<Domain> {
const domainModel = new DomainModel<Domain>({name: params.name, objects: []});
const domainCreated = await domainModel.save().then();
return domainCreated;
}
}
控制器(POST)
@Post()
@SuccessResponse("201", "Created")
@Response<ValidateErrorJSON>(422, "Validation Failed")
@Response<UnauthorizedErrorJson>(401, "Unauthorized")
@Security("api_key")
public async createDomain(@Body() requestBody: DomainCreate): Promise<Domain> {
const createdDomain = await new DomainService().create(requestBody);
if (createdDomain) this.setStatus(201);
else this.setStatus(500);
return createdDomain;
}
测试:
POST http://localhost:3000/domains
{
"name": "D1"
}
反应:
{
"name": "D1",
"_id": "6291e582ade3b0f8be6921dd",
"__v": 0
}
预期响应:
{
"name": "D1",
"id": "6291e582ade3b0f8be6921dd"
}
可以有不同的方法,但您可以选择normalize-mongoose。它将去除_id
,__v
,并得到id
;
那么,在你的模式中你可以像这样添加这个插件:
import normalize from 'normalize-mongoose';
const DomainSchema = new Schema<Domain>({
name: { type: String, required: true },
});
DomainSchema.plugin(normalize);
const DomainModel = mongoose.model<Domain>("Domain", DomainSchema);
export { DomainModel, DomainSchema };