Here is my document and Employee
is a collection in mongoDB database
@Document(collection = "Employee")
public class Employee {
@Id
private String id;
private String eId;
private String firstName;
private String lastName;
private String emailId;
private int grpId;
}
This is the controller class
@RestController
@CrossOrigin(origins = "*")
public class EmployeeController {
@Autowired
private EmployeeService service;
@GetMapping("/employee")
public ResponseEntity<?> getAllEmployee(){
List<Employee> employees;
employees = service.getAllEmployees();
return new ResponseEntity<List<Employee>>(employees, HttpStatus.OK);
}
@PostMapping("/employee")
public void newEmployee(@RequestBody Employee employee){
service.newEmployee(employee);
}
}
This is the service class
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepo;
public List<Employee> getAllEmployees(){
return employeeRepo.findAll();
}
public void newEmployee(Employee employee){
employeeRepo.save(employee);
}
}
This is the repository Interface
@Repository
public interface EmployeeRepository extends MongoRepository<Employee,String> {
}
This is my post request to http://localhost:8080/employee
8080
is the port on which the application is running
{
"eId": "01abc",
"firstName": "your_firstName",
"lastName": "your_lastName",
"emailId": "[email protected]",
"grpId": 1
}
Once the post request has been fulfilled when I use get request to fetch all the employees I get:
{
"id": "63f6f0ffb84be0661b8d35a0",
"firstName": "your_firstName",
"lastName": "your_lastName",
"emailId": "[email protected]",
"grpId": 1,
"eid": null
}
I am unable to figure out why eId
is null
if I am passing the eId
as "01abc"
I tried searching the stack overflow for this but could not find a solution
2
Answers
Ok, so according to your HTTP/POST request, I can see you’re not exclusively passing the ‘Id’ field as part of the JSON. So unless you’re auto-generating it somehow, here are some tips I could give to try out and see what works:
I hope one of these suggestions helps 🙂
Change your id variable type to Long or UUID with @Generated and then
change your post request to