En mi aplicación Nest, recibo un error de tipo cuando llamo a _id en el user porque mongoose define el _id automáticamente y, por lo tanto, no está presente en mi esquema que se define como tipo para la promesa.
Cuando el tipo de promesa se cambia a cualquiera como Promise<any> , entonces no hay ningún tipo de error.
async create(createUserDto: CreateUserDto): Promise<User> { const createdUser = await new this.userModel(createUserDto).save(); return createdUser; } pero quiero saber si esta es la forma correcta o debería estar haciendo otra cosa.
No quiero definir _id en el esquema para resolver este problema.
@Prop({ auto: true}) _id!: mongoose.Types.ObjectId;usuario.esquema.ts
// all the imports here.... export type UserDocument = User & Document; @Schema({ timestamps: true }) export class User { @Prop({ required: true, unique: true, lowercase: true }) email: string; @Prop() password: string; } export const UserSchema = SchemaFactory.createForClass(User);usuarios.controlador.ts
@Controller('users') @TransformUserResponse(UserResponseDto) export class UsersController { constructor(private readonly usersService: UsersService) {} @Post() async create(@Body() createUserDto: CreateUserDto) { const user = await this.usersService.create(createUserDto); return user._id; } }usuarios.servicio.ts
// all the imports here.... @Injectable() export class UsersService { constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {} async create(createUserDto: CreateUserDto): Promise<User> { const createdUser = await new this.userModel(createUserDto).save(); return createdUser; } }