簡體   English   中英

Spring Boot MongoRepository findAll() 返回空數組

[英]Spring Boot MongoRepository findAll() returns empty array

我有一個連接到本地 Mongo 數據庫的 Spring 引導應用程序,但是當我嘗試通過請求http://localhost:8080/api/v1/users從集合中獲取所有文檔時,它返回一個空數組。 我也沒有任何連接錯誤。 我已經讀到問題可能出在集合名稱上,但是當我指定集合名稱時(現在 MongoDB 中的集合名稱與模型中的相同),它仍然返回一個空數組。 還有什么可能是錯的?

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
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}

出現問題是因為您的 model 中沒有明確給出集合名稱。您可以像下面這樣更改代碼嗎

@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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM