When I try to use the findById
method from MongoRepository with a string passed in, I get an error with the mapper which leads to no results being returned, even though such exists.
Here is my project's structure and files:
Entity Post.java
@Document("posts")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Post {
@Id
private String Id;
private Integer userId;
private String content;
private Integer likes;
private Integer dislikes;
}
Repository PostRepository.java
public interface PostRepository extends MongoRepository<Post, String> {
}
Service PostService.java
@Service
public class PostService {
@Autowired
private PostRepository repository;
public List<Post> getPosts() {
return repository.findAll();
}
public Post getPostById(String id) {
return repository.findById(id).orElse(null);
}
public Post savePost(Post post) {
return repository.save(post);
}
public void deletePostById(String id) {
repository.deleteById(id);
}
}
Controller PostController.java
@RestController
@RequestMapping("/posts")
public class PostController {
@Autowired
private PostService service;
@Autowired
private StreamBridge streamBridge;
@GetMapping("")
public List<Post> getPosts() {
return service.getPosts();
}
@GetMapping("/{postId}")
public Post getPostById(@PathVariable String postId) {
return service.getPostById(postId);
}
@PostMapping("/createPost")
public Post createPost(@RequestBody Post post) {
streamBridge.send("postCreated-out-0", post.getUserId());
return service.savePost(post);
}
@DeleteMapping("/{postId}")
public void deletePostById(@PathVariable String postId) {
service.deletePostById(postId);
}
}
When I try running either a GET
such as localhost:9192/posts/62a76719145e644e5b640327
or a DELETE localhost:9192/posts/62a76719145e644e5b640327
, where 62a76719145e644e5b640327
is a correct id associated with a entry in the document in MongoDB I get this error in the console:
[nio-9192-exec-2] o.s.d.mongodb.core.convert.QueryMapper : Could not map 'Post.id'. Maybe a fragment in 'String' is considered a simple type. Mapper continues with id.
I also tried writing a custom query using the @Query
annotation that overwrites the default findById as such:
@Override
@Query("{ 'id' : ?0}")
Optional<Post> findById(String s);
And I still get the same error. I am using spring-boot-starter-data-mongodb
version 2.7.0 and I am running MongoDB locally.
EDIT: Forgot to mention that the same thing happens when using the deleteById
method
CodePudding user response:
i think the problem is in the identifier u named it with capital I replace Id in posts document with id ? give it a try... it will work