g_m
g_m

Reputation: 526

How to return the fields defined by the interface not by the mongoose schema

How can I return "id" insted of "_id" and without "__v" to the client with express, mongoose and TypeScript?

My code below:

Interface

export default interface Domain {
  name: string;
  objects: DomainObject[]
}

Creation Interface

export default interface DomainCreate {
    name: string
}

Mongoose Model

const DomainSchema = new Schema<Domain>({
  name: { type: String, required: true },
});

const DomainModel = mongoose.model<Domain>("Domain", DomainSchema);
export { DomainModel, DomainSchema };

Service

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;
  }
}

Controller (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;
  }

Test:

POST http://localhost:3000/domains
{
  "name": "D1"
}

Response:

{
  "name": "D1",
  "_id": "6291e582ade3b0f8be6921dd",
  "__v": 0
}

Expected response:

{
  "name": "D1",
  "id": "6291e582ade3b0f8be6921dd"
}

Upvotes: 0

Views: 604

Answers (1)

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

There can be different ways to do it, but you can choose normalize-mongoose. It will remove _id, __v and gives you id;

So, in your schema you can add this plugin like this:

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 };

Upvotes: 1

Related Questions