【发布时间】:2020-08-04 01:41:07
【问题描述】:
我是 SpringBoot 和 MongoDB 的初学者 我尝试使用 GET 方法在 MongoDB 中查找我的所有玩家。 我的程序适用于所有方法:PUT、POST、DELETE 和 GET("/{ID}) 但不适用于 GET() 我不明白我在哪里犯了错误,或者问题出在哪里,因为我尝试了很多方法,例如:更改顺序并将 Get() getAllPlayers 放在 getPlayerByID 之后,或者我使用了@Get("/"),为此我收到了错误405。 请问你能帮帮我吗?! 我的 playerController 是:
package thesisMongoProject.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import thesisMongoProject.Player;
import thesisMongoProject.Repository.PlayerRepository;
@RestController
@RequestMapping("/player")
public class PlayerController {
@Autowired
private PlayerRepository repo;
//Get All Players
@GetMapping
public List<Player> getAllPlayers() {
return repo.findAll();
}
//Getting Player ID
@GetMapping("/{nickname}")
public Player getPlayerByID(@PathVariable String nickname){
return repo.findById(nickname).get();
}
//Delete Players
@DeleteMapping
public String deleteAllPlayers(){
repo.deleteAll();
return "Deleted!";
}
//Create Player
@PostMapping
public ResponseEntity<?> createPlayer(@RequestBody Player player){
repo.save(player);
return ResponseEntity.status(201).body("Created!");
}
//Delete player By ID
@DeleteMapping("/{nickname}")
public ResponseEntity<?> deletePlayerByID(@PathVariable String nickname){
try {
Player p = repo.findById(nickname).get();
return ResponseEntity.ok(p);
} catch (Exception e) {
return ResponseEntity.status(404).body("Not Found!");
}
}
//Update Player By ID
@PutMapping("/{nickname}")
public ResponseEntity<?> updatePlayerByID(
@PathVariable("nickname")String nickname,
@RequestBody Player player){
try {
player.setNickname(nickname);
repo.save(player);
return ResponseEntity.ok(player);
} catch (Exception e) {
return ResponseEntity.status(404).body("Not Found!");
}
}
}
【问题讨论】:
-
请将您遇到的错误添加到问题中。
-
{ "timestamp": "2020-04-21T11:28:21.734+0000", "status": 500, "error": "Internal Server Error", "message": "查询失败错误代码 2 和错误消息 'Field 'locale' is invalid in: { locale: \"player\" }' on server localhost:27017; 嵌套异常是 com.mongodb.MongoQueryException: 查询失败,错误代码 2 和错误消息'Field 'locale' 在服务器 localhost:27017" 上的 { locale: \"player\" }' 无效,
-
你的日志有错误,检查并添加。可能需要在启用
--debug的情况下重新运行。 -
能否请您在 Gitub 中查看我的代码:github.com/saharsahbaa/MyPlayers.git。我不明白你指向的这个日志在哪里
-
对您的 mongodb 的查询是错误的,这意味着您的 MongoDB 存在设置问题。见stackoverflow.com/questions/59532821/…
标签: java mongodb spring-boot spring-mvc postman