【发布时间】:2019-12-13 15:09:51
【问题描述】:
我正在开发一个 kotlin 反应式 spring-boot mongodb 项目。我正在尝试更新文档,但效果不佳。
我的问题与stackoverflow中的以下问题非常相似。
Spring reactive mongodb template update document partially with objects
所以我在 mongo 中有一个文档
{
"id": 1,
"name": "MYNAME",
"email": "MYEMAIL",
"encryptedPassword": "12345",
...........................
}
当我使用以下标头之一在 uri localhost:8080/user/1 上调用 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 reactive mongodb template update document partially with objects 给出的建议。
我的代码会更新,但它会更新为我的 User 类的初始构造函数。
有人可以帮忙吗?
【问题讨论】:
标签: mongodb kotlin spring-data reactor