I'm just getting to know the possibilities of Kotlin and mongoDB.
I am writing a method that returns the name of the street after the ID.
Everything works, but I find it quite sloppy.
Empty String initialization, returning more data from the collection than I would like.
How do I straighten it? Could it be made into some expression body one-liner?
fun getStreetNameByStreetId(id: String): String {
val query = Query()
query.fields().include("name")
query.addCriteria(Criteria.where("_id").`is`(id))
var streetName = ""
mongoTemplate.executeQuery(
query, STREET_COLLECTION
) { document: Document ->
streetName = document.getValue("name").toString()
}
return streetName
}
1 Answer 1
This is how it would look in Java:
public String getStreetNameByStreetId(String id) {
Query streetNameByStreetId = Query.query(
Criteria.where("_id").is(id));
byStreetId.fields().include("name");
return mongoTemplate.find(streetNameByStreetId, Street.class)
.get(0).getName();
}
I realize you are looking for how this would look in Kotlin, but it should look very similar. Also, for simple CRUD operations you might want to consider just using a MongoRepository and leveraging the Domain Specific Language (DSL).
streetName
with an asynchronous callback, so you're returning the original empty String before the callback even has a chance to be called. e.g. stackoverflow.com/questions/57330766/… \$\endgroup\$