Method save does not return the entire model
Problem
Issue type: [ ] question [x] bug report [ ] feature request [ ] documentation issue Database system/driver: [ ] `cordova` [ ] `mongodb` [ ] `mssql` [ ] `mysql` / `mariadb` [ ] `oracle` [x] `postgres` [ ] `sqlite` [ ] `sqljs` [ ] `react-native` [ ] `expo` TypeORM version: [ ] `latest` [ ] `@next` [0.2.8] `0.x.x` (or put your version here) Steps to reproduce or a small repository showing the problem: [code block] Using the PUT method, a part of the model comes to us. The save method accepts `DeepPartial<Entity>`, but in this case it does not return the entire model. <!-- To answer those questions you need to put "x" inside the square brackets, for example: [x] `mysql` [ ] `postgres` Also, please format your code properly (by taking code blocks into [code block]) !>
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Ensure save method returns complete model after update
The save method in TypeORM is designed to accept a DeepPartial of the entity, which means it only requires a subset of the entity's properties to perform an update. However, it does not automatically return the entire model after the save operation. This behavior can lead to confusion when expecting the complete updated entity to be returned.
Awaiting Verification
Be the first to verify this fix
- 1
Modify the save method to fetch the complete entity
After calling the save method, retrieve the complete entity from the database using its ID to ensure you get the entire model with all properties populated.
typescriptconst savedEntity = await repository.save(partialEntity); const completeEntity = await repository.findOne(savedEntity.id); - 2
Implement a custom save function
Create a custom save function that wraps the save method and automatically fetches the complete entity after saving.
typescriptasync function saveAndReturnComplete(entity) { const savedEntity = await repository.save(entity); return await repository.findOne(savedEntity.id); } - 3
Update API endpoint to use the custom save function
Ensure that the API endpoint that handles the PUT request uses the new custom save function to return the complete entity.
typescriptapp.put('/entity/:id', async (req, res) => { const entity = req.body; const completeEntity = await saveAndReturnComplete(entity); res.json(completeEntity); }); - 4
Test the updated functionality
Run tests to confirm that the API now returns the complete model after an update. Check that all properties are present in the response.
typescriptconst response = await request(app).put('/entity/1').send(partialEntity); expect(response.body).toHaveProperty('completeProperty1'); expect(response.body).toHaveProperty('completeProperty2');
Validation
Confirm that after performing a PUT request, the response contains the complete model with all properties populated. Validate against the database to ensure consistency.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep