Issue
I have already done connect MongoDB using application.properties. But I want to connect MongoDB through mongoose.
This is my current configuration
This is DB Connection url setting in application.properties;
spring.data.mongodb.uri =mongodb+srv://hans123:[email protected]/?retryWrites=true&w=majority
spring.data.mongodb.database=test
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
Solution
Model Class
@Document
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
@Id
@Indexed
private String id;
@Indexed
private String address;
@Indexed
private String name;
@Indexed
private String email;
@Indexed
private String password;
@Indexed
private String role;
}
Repository Class
public interface userReporsitory extends MongoRepository<User,String> {
Optional<User> findByEmail(String email);
List<User> findAllByRole(String role);
}
Service Class
@AllArgsConstructor
@Service
public class userService {
private userReporsitory userReporsitory;
public User saveUser(User user){
return userReporsitory.save(user);
}
public User login(User user){
User response = userReporsitory.findByEmail(user.getEmail()).orElseThrow(()->new RuntimeException("User Not Found"));
if(!response.getPassword().equals(user.getPassword())){
throw new RuntimeException("Bad Credincials");
}
return response;
}
public List<User> findAllUsers(){
return userReporsitory.findAllByRole("user");
}
}
Controller Class
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("api/v1/user")
public class userController {
private userService userService;
@PostMapping("/create")
public ResponseEntity<User> save(@RequestBody User user){
HttpStatus status = HttpStatus.EXPECTATION_FAILED;
User response = userService.saveUser(user);
if(response != null){
status = HttpStatus.CREATED;
}
return new ResponseEntity<>(response, status);
}
@PostMapping("/login")
public ResponseEntity<User> login(@RequestBody User user){
return new ResponseEntity<>(userService.login(user),HttpStatus.ACCEPTED);
}
@GetMapping("/userList")
public ResponseEntity<List<User>> userList(){
return new ResponseEntity<>(userService.findAllUsers(),HttpStatus.ACCEPTED);
}
}
Answered By - Anonymous
Answer Checked By - David Goodson (JavaFixing Volunteer)