Within my current project, I am encountering a type error when attempting to call _id
on the user
object. This issue arises because mongoose automatically defines the _id
, meaning it is not present in my schema where the promise is defined.
Upon changing the promise type to Promise<any>
, the type error disappears.
async create(createUserDto: CreateUserDto): Promise<User> {
const createdUser = await new this.userModel(createUserDto).save();
return createdUser;
}
I am uncertain if this is the correct approach or if there is an alternative solution that should be implemented instead. I would prefer not to add _id
to the schema to resolve this issue.
@Prop({ auto: true})
_id!: mongoose.Types.ObjectId;
user.schema.ts
// list of imports...
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);
users.controller.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;
}
}
users.service.ts
// list of imports....
@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;
}
}