Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

spring - Springboot Mongo reactive repository unable to update nested list

I wanted to update a nested list but I experience a strange behavior where I have to call method twice to get it done...

Here is my POJO:

@Document(collection = "company")
data class Company (
        val id: ObjectId,
        @Indexed(unique=true)
        val name: String,
        val customers: MutableList<Customer> = mutableListOf()
        //other fields
)

Below is my function from custom repository to do the job which I based on this tutorial

override fun addCustomer(customer: Customer): Mono<Company> {
    val query = Query(Criteria.where("employees.keycloakId").`is`(customer.createdBy))
    val update = Update().addToSet("customers", customer)
    val upsertOption = FindAndModifyOptions.options().upsert(true)
    //if I uncomment below this will work...
    //mongoTemplate.findAndModify(query, update, upsertOption, Company::class.java).block()
    return mongoTemplate.findAndModify(query, update, upsertOption, Company::class.java)
}

In order to actually add this customer I have to either uncomment the block call above or call the method two times in the debugger while running integration tests which is quite confusing to me

Here is the failing test

@Test
fun addCustomer() {
    //given
    val company = fixture.company
    val initialCustomerSize = company.customers.size

    companyRepository.save(company).block()

    val customerToAdd = CustomerReference(id = ObjectId.get(),
            keycloakId = "dummy",
            username = "customerName",
            email = "email",
            createdBy = company.employees[0].keycloakId)
    
    //when, then
    StepVerifier.create(companyCustomRepositoryImpl.addCustomer(customerToAdd))
            .assertNext { updatedCompany -> assertThat(updatedCompany.customers).hasSize(initialCustomerSize + 1) }
            .verifyComplete()

}

java.lang.AssertionError: Expected size:<3> but was:<2> in:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found out the issue.

By default mongo returns entity with state of before update. To override it I had to add:

        val upsertOption = FindAndModifyOptions.options()
            .returnNew(true)
            .upsert(true)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...