Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
Sharing typescript interfaces between client and server mongoose model

I'm trying to share some base interfaces between the client code and the server code. I'm having problems when using the interfaces to create data models in mongoose.

The problem I have is how to access the document._id property in the client. I can't add _id to the User interface without causing compilation errors and I can't access _id without declaring it.

My project layout:

/src
-/client
--/user.service.ts
-/server
--/models
---/user.model.ts
-/common
--/common.d.ts

user.service.ts

import { User } from 'common'

 deleteUser(user: User): Promise<User> {
   return this.http.delete( 'http://someurl/api/users' + user._id )
     .toPromise()
     .then( resp => resp.json().data as User )
     .catch( err => this.errorHandler(err) );
 }

user.model.ts

import { model, Schema, Document } from 'mongoose';
import { User } from 'common';

let UserSchema = new Schema {
  firstName: String,
  lastName: String,
  email: String
}

export interface UserDocument extends User, Document { }

export var UserModel:Model<UserDocument> = model<UserDocument>('Users', UserSchema);

common.d.ts

declare module 'common' {
  export interface User {
    firstName: string;
    lastName: string;
    email: string;
  }
}

Thanks for the help

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can declare _id as optional:

export interface User {
    _id?: string;
    firstName: string;
    lastName: string;
    email: string;
}

Or you can have another interface for a user with id:

export interface PersistedUser extends User {
    _id: string;
}

And cast to it whenever needed.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda