How to get a data from mongoDB with the _id in Kotlin

Viewed 34

I'm new in programming and I'm had having some problems to create an API for Kotlin getting data from a existing DB from mongoDB to my API. I'm making Tests and I want to return a data with it Id, but I can't. I'm using the SpringBoot, JPA, and mongoDB Data. The host is my machine, the database name is ArthurLeywin, and the collection name is Capitulos. I'm receiving the error status=404, error=Not Found, path=/ArthueLeywin/Capitulos/6306e6417d5b2e259951f292}

The code of the Test is

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension::class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class TbateMobileReederApplicationTests @Autowired constructor(
    private val capituloRepository: CapituloRepository,
    private val restTemplate: TestRestTemplate
) {
    private val defaultCapituloId : ObjectId = ObjectId("6306e6417d5b2e259951f292")
        //ObjectId.get()

    @LocalServerPort
    protected var port: Int = 27017

    private fun getRootUrl(): String? = "http://localhost:$port/ArthueLeywin/Capitulos"


    @Test
    fun `should return single cap by id`() {
        val response = restTemplate.getForObject(
            getRootUrl() + "/$defaultCapituloId",
            Object::class.java
        )
        val titleResponse = response.toString()

        println(titleResponse)
    }

}

My controller, if it's needed is

@RestController
@RequestMapping("/Capitulos")
class CapituloController (
    private val capituloRepository : CapituloRepository
){
    @GetMapping
    fun getAllCapitulos() : ResponseEntity<List<Capitulo>>{
        val capitulos = capituloRepository.findAll()
        return ResponseEntity.ok(capitulos)
    }
    @GetMapping("/{id}")
    fun getOneCapitulo(@PathVariable("id") id: String): ResponseEntity<Capitulo> {
        val capitulo = capituloRepository.findOneById(ObjectId(id))
        return ResponseEntity.ok(capitulo)
    }

    @PostMapping
    fun createCapitulo (@RequestBody request: CapituloRequest) : ResponseEntity<Capitulo>{
        val capitulo = capituloRepository.save(Capitulo(
            nomeCapitulo = request.nomeCapitulo,
            urlString = request.urlString,
            novelTexto = request.novelTexto
        ))
        return ResponseEntity(capitulo, HttpStatus.CREATED)
    }

}

As I said I'm new in this, so please help me with explanations <3

0 Answers
Related