【发布时间】:2021-03-07 06:45:40
【问题描述】:
我有一个连接到本地 Mongo 数据库的 Spring Boot 应用程序,但是当我尝试通过请求 http://localhost:8080/api/v1/users 从集合中获取所有文档时,它返回一个空数组。我也没有任何连接错误。我已经读到问题可能出在集合名称上,但是当我指定集合名称时(现在 MongoDB 中的集合名称与模型中的相同),它仍然返回一个空数组。还有什么问题?
型号:
@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
}
控制器:
@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
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> find() {
return userRepository.findAll();
}
}
存储库:
public interface UserRepository extends MongoRepository<User, String> {
public User findByEmail(String email);
}
直接来自 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
}
编辑
问题出在我的连接属性上。
之前:
# application.yml, started using yaml just for better readability,
# should work as fine with application.properties
spring:
data:
mongodb:
url: mongodb://localhost:27017/{dbname}
之后:
# application.yml
spring:
data:
mongodb:
host: localhost
port: 27017
database: {dbname}
【问题讨论】:
-
您的应用程序中有多个配置文件吗?喜欢多个数据库?本地还是其他?条目可能存在于一个数据库中,但不存在于其他数据库中??
-
不,我已连接到一个数据库,我正在通过
application.properties文件设置连接,这是我唯一拥有的一行:spring.data.mongodb.url=mongodb://localhost:27017/{dbname}(数据库名称有效)@kakabali -
我可以看到它仅与连接有关,但这不能作为问题的答案,而只是一个愚蠢的错误和配置问题
标签: java spring mongodb spring-boot