1

我正在开发一个 kotlin 反应式 spring-boot mongodb 项目。我正在尝试更新文档,但效果不佳。

我的问题与stackoverflow中的以下问题非常相似。

Spring响应式mongodb模板更新文档部分包含对象

所以我在 mongo 有一个文件

{
  "id": 1,
  "name": "MYNAME",
  "email": "MYEMAIL",
  "encryptedPassword": "12345",
  ...........................
}

当我localhost:8080/user/1使用以下标头之一在 uri 上调用 PATCH 时

{
  "name": "NEW NAME"
}
{
  "email": "NEW EMAIL"
}

我只想用收到的字段更新我的文档。

我的处理程序代码

fun update(serverRequest: ServerRequest) =
        userService
                .updateUser(serverRequest.pathVariable("id").toLong(), serverRequest.bodyToMono())
                .flatMap {
                    ok().build()
                }

我的服务实现代码

override fun updateUser(id: Long, request: Mono<User>): Mono<UpdateResult> {
    val changes = request.map { it -> PropertyUtils.describe(it) }
    val updateFields: Update = Update()
    changes.subscribe {
        for (entry in it.entries) {
            updateFields.set(entry.key, entry.value)
        }
    }
    return userRepository.updateById(id, updateFields)
}

我的存储库代码

    fun updateById(id: Long, partial: Update) = template.updateFirst(Query(where("id").isEqualTo(id)), partial, User::class.java)

我的用户代码

@Document
data class User(
        @Id
        val id: Long = 0,
        var name: String = "",
        val email: String = "",
        val encryptedPassword: ""
)

我遵循了Spring 响应式 mongodb 模板更新文档部分带有对象的建议。

我的代码会更新,但它会更新到我的User类的初始构造函数。

有人可以帮忙吗?

4

2 回答 2

0

我想您应该将此问题视为在 Java/Kotlin 中修补对象的一般问题。我发现了一篇关于此的文章:https ://cassiomolin.com/2019/06/10/using-http-patch-in-spring/#json-merge-patch 。即使您不会更新部分对象,也不会对应用程序的性能产生如此大的影响。

于 2019-08-06T07:09:54.733 回答
0

I figured out how to partially update my data.

First I changed the body request to string. (using bodyToMono(String::class.java)

Then I changed the changed JSON string to JSONObject(org.json).

And for each of its JSONObject's key I created Update that will be the partial data to update my entity.

Following is how I implemented this.

override fun updateUser(id: Long, request: Mono<String>): Mono<UpdateResult> {
    val update = Update()
    return request.map { JSONObject(it) }
            .map {
                it.keys().forEach { key -> update.set(key, it[key]) }
                update
            }
            .flatMap { it -> userRepository.updateById(id, it) }

}

Please share more idea if you have more 'cleaner' way to do this. Thank you

于 2019-08-16T07:19:13.023 回答