0

In the below code I want to generate addrId automatically and show it in the Person document, but the addrId is not showing up in the document.

@Document
public class Person {
    
  @Id
  String id;

  List<Address> addresses;
        
 }    

public class Address {
    
    @Id
    String addrId;

    String street;
  }    


public class Example {
    
    public Person createAddress(Person person, Address addr) {
            Set<Address> addresses = new HashSet<>();
            addresses.add(addr);

    
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(id));
            Person person = mongoTemplate.findOne(query, Person.class);
            person.setAddresses(addresses);
    
            return mongoTemplate.save(person);
        }
    }

Expected document with addrId:

{
  "_id" : ObjectId("592c7029aafef820f432c5f3"),
  "_class" : "tutorial.mongodb.documents.Person",
  "addresses" : [{
    "addrId" : ObjectId("321c7029aafed220f432d321"),
    "street" : "London street"
  }]
} 

but addrId is not getting displayed as seen in the below document:

{
      "_id" : ObjectId("592c7029aafef820f432c5f3"),
      "_class" : "tutorial.mongodb.documents.Person",
      "addresses" : [{
        "street" : "London street"
      }]
    }

1 Answer 1

0

This works for me as expected:

 public String createAddress(Person person, Address addr) {

        addr.setAddrId(String.valueOf(UUID.randomUUID()));

        List<Address > addrs = person.getAddresses();
        addrs.add(addr);

        person.setAddresses(addrs);
        
        mongoTemplate.save(person);

        return addr.getAddrId();
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.