Litote / kmongo

[deprecated] KMongo - a Kotlin toolkit for Mongo
https://litote.org/kmongo/
Apache License 2.0
781 stars 74 forks source link

Returnig the Saved Object on Success instead on wasAcknowledged #367

Closed Morons closed 2 years ago

Morons commented 2 years ago

Consider this:

override suspend fun createUser(user: User): Boolean {
    return usersDb.insertOne(user).wasAcknowledged()
}

this returns Boolean upon success or failure!

What is needed

override suspend fun createUser(user: User): User {
    return usersDb.insertOne(user).savedRecord()
}

return the record saved, including the important ObjectId if ONLY the ObjectId is returned that will help tremendously

Doing it the current way will need another call to the DB and searching for the Object as you still do not have the ObjectId therefore trying to locate the recodr can lead to errors - especailly if there is no unique field stored

Note:

Id rather have MongoDb produce the ObjectId instead of me!

@BsonId
val userId: String = ObjectId().toString()
zigzago commented 2 years ago

InsertOneResult has a [getInsertedId](https://mongodb.github.io/mongo-java-driver/4.5/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html#getInsertedId()) method. Do you get the ObjectId with it?

https://mongodb.github.io/mongo-java-driver/4.5/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html