Spring React MongoDB模板使用对象部分更新文档 [英] Spring reactive mongodb template update document partially with objects
问题描述
我有一些要在mongo db中更新的类(文档)
I have some class (document) to update in mongo db
文档存储在mongo中(实际示例更为复杂):
The document stored in mongo (real example more complicated):
{
"id": "5ba6b0576cba836aa43ab379",
"firstName": "First Name",
"lastName": "Last Name",
"mobile": "123456789"
....................
....................
....................
"address": "some address"
}
比方说,我在上面的所有这些字段中都有Foo类.
Let's say, I have class Foo with all these fields above.
我从外部部分对象接收(Foo只有3个值,所有其他值均为空),例如:
I receive from outside partial object (Foo with only 3 value, all other values are null), e.g.:
{
"id": "5ba6b0576cba836aa43ab379",
"mobile": "987654321",
"address": "other address"
}
我想更新文档,但仅包含接收到的字段.
I want to update document, but with received fields only.
我发现只有一个选项可以使用reactmongotemplate手动进行. 我正在寻找更多的不错"的方法,而无需手动创建Update对象.像这样:
I found only option to do it manually with reactivemongotemplate. I am looking for more "nice" way without creating manually Update object. Something like:
reactivemongotemplate.updateFirst(
Query.query(Criteria.where("id").is("5ba6b0576cba836aa43ab379")),
partialFoo // (object of class is Foo)
)
有人知道有什么方法吗?
Does anybody knows any way to do this?
推荐答案
我不知道这是否是最好的"方法,但是对于我正在开始的其他Web服务,我一直在尝试在内部简化PATCH和PUT方法,然后使用org.apache.commons.beanutils.PropertyUtils
库通过Map进行操作,然后创建要传递给ReactiveMongoTemplate
的Update对象,或多或少是这样的:
I don't know if this is the "nicest" way to do it, but for a rest webservice I'm starting, I've been trying to simplify internally the PATCH and PUT methods and I do it using a Map using the org.apache.commons.beanutils.PropertyUtils
library and then I create the Update object I am passing to the ReactiveMongoTemplate
, more or less like this:
Map<String, Object> changes = PropertyUtils.describe(myDto);
// ... check the fields that must be sets and other business rules ...
Update updateFields = new Update();
for(Map.Entry<String, Object> entry : changes.entrySet()){
updateFields.set(entry.getKey(), entry.getValue());
}
reactivemongotemplate.updateFirst(query(where("id").is(myId)), updateFields, MyEntity.class)
这意味着您的MyDto
类具有您需要的每个字段的getter和setter,但是到目前为止,它运行良好.
This implies that your MyDto
class has the getters and setters for each field you need, but it is working pretty well so far.
这篇关于Spring React MongoDB模板使用对象部分更新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!