https://kotlinlang.org logo
#kmongo
Title
# kmongo
i

IsaacMart

06/16/2022, 2:19 PM
Hello team, am new to mongodb and am using it for my ktor project. How can i return the inserted document back to client after insertion. I need the doc to store it in room
s

Szymon Kaczorowski

06/16/2022, 7:30 PM
You could use this method and make sure to set options to upsert and return new document https://litote.org/kmongo/dokka/kmongo/org.litote.kmongo/com.mongodb.client.-mongo-collection/find-one-and-update.html
i

IsaacMart

06/16/2022, 7:53 PM
I have managed to insert document into my Db but when i return the insertedId, its coming out null. The acknowledgement was made but id is null.how is that possible?
s

Szymon Kaczorowski

06/16/2022, 7:55 PM
As you used insert it returns only Id so to be able to return full document you either have to build it with Id or you have to use trick with
findoneandupdate
i

IsaacMart

06/17/2022, 4:57 AM
I want to get the id of the inserted document so that i can use the trick. but my insertId returns null. In my user POJO i have initialised @Bson val id:String= ObjectId.toString() Could this be the problem?How do i fix it.
Finaly found a work around on the issue. Regarding retrieving the id from the inserted document after acknowledgement, you have to make an insertion then after the acknowledgement, retrieve the inserted id through another query using anotger unique field. Normally the inserted document returns a Boolean of acknowledgement and the insertedId. But you will notice that the insertedId is null even when acknowledgement is true.
24 Views