I have a Spring Boot application connected to the local Mongo database, but when I try to fetch all the documents from a collection by requesting http://localhost:8080/api/v1/users
it returns an empty array. I don't have any connection errors as well. I've read that the problem could've been with collection names, but when I specified collection name (and now collection name in MongoDB is the same as in the model), it still returns an empty array. What else could've been wrong?
Model:
@Document(collection = "users")
public class User {
@Id
private String id;
private String username;
private String email;
private String password;
private String birthdate;
private int chest;
private int weight;
private int height;
private boolean gender;
// constructors, getters and setters omitted
}
Controller:
@RestController
@RequestMapping("api/v1/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<User> findAll() {
return userService.find();
}
}
Service:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> find() {
return userRepository.findAll();
}
}
Repository:
public interface UserRepository extends MongoRepository<User, String> {
public User findByEmail(String email);
}
Straight from MongoDB:
> db.users.find().pretty()
{
"_id" : ObjectId("60002a15803d9027a459b7b6"),
"username" : "name",
"email" : "zaaas@sasasfa.aaa",
"birthdate" : "1999-10-2",
"weight" : 67,
"height" : 175,
"chest" : 87,
"gender" : true,
"__v" : 0
}
{
"_id" : ObjectId("60002be21da6d929fa45c9f2"),
"username" : "aye",
"email" : "zaaas@sasasfsdsa.aaa",
"birthdate" : "1999-10-2",
"weight" : 65,
"height" : 180,
"chest" : 80,
"gender" : true,
"__v" : 0
}
The problem was with my connection properties.
Before:
# application.yml, started using yaml just for better readability,
# should work as fine with application.properties
spring:
data:
mongodb:
url: mongodb://localhost:27017/{dbname}
After:
# application.yml
spring:
data:
mongodb:
host: localhost
port: 27017
database: {dbname}
The issue arises because the collection name is not explicitly given in your model.Can you change your code like below
@Document(collection = "User")
public class User {
@Id
private String id;
private String username;
private String email;
private String password;
private String birthdate;
private int chest;
private int weight;
private int height;
private boolean gender;
// constructors, getters and setters omitted
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.