Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

472
Views
Cómo devolver los campos definidos por la interfaz, no por el esquema de mongoose

¿Cómo puedo devolver "id" en lugar de "_id" y sin "__v" al cliente con express, mongoose y TypeScript?

Mi código a continuación:

Interfaz

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

Interfaz de creación

 export default interface DomainCreate { name: string }

modelo de mangosta

 const DomainSchema = new Schema<Domain>({ name: { type: String, required: true }, }); const DomainModel = mongoose.model<Domain>("Domain", DomainSchema); export { DomainModel, DomainSchema };

Servicio

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

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

Prueba:

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

Respuesta:

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

Respuesta esperada:

 { "name": "D1", "id": "6291e582ade3b0f8be6921dd" }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Puede haber diferentes formas de hacerlo, pero puede elegir normalize-mongoose . Eliminará _id , __v y le dará una id ;

Entonces, en su esquema puede agregar este complemento como este:

 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 };
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!