Skip to content

Repository lookups by DocumentReference returning empty results #4033

Closed
@maxim04

Description

@maxim04

Using spring-boot-starter-data-mongodb:2.6.6

  • spring-boot-starter:2.6.6
  • mongodb-driver-sync:4.4.2
  • spring-data-mongodb: 3.3.3

I have the following code below with 2 documents, User and Product. Product has a DocumentReference to a User object. Using a repository for each document, lookups by id of type String work as expected. But lookups for Product based on the User DocumentReference using an id of type String return 0 results. However if I do the same lookup using an id of type ObjectId I get back the correct set of results.

I also discovered if I use @MongoId(FieldType.STRING) for the id property, the lookups for Product based on the User DocumentReference using an id of type String returns the correct results, but now lookups for the Product or User using id of type String returns empty results. To get back the right set of results I have to lookup Product or User with an id of type ObjectId, essentially the reverse behaviour of the first observation.

Is it supposed to behave like this? I would expect the same behaviour when looking up documents using an id of type String.

The code:

@SpringBootApplication
@EnableMongoRepositories
public class Demo1Application implements CommandLineRunner {

    @Autowired
    UserRepository userRepository;
    @Autowired
    ProductRepository productRepository;

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        userRepository.deleteAll();
        productRepository.deleteAll();

        User user = new User();
        userRepository.save(user);

        Product product = new Product();
        product.setOwner(user);
        productRepository.save(product);

        List products1 = productRepository.findAllByOwner_Id(user.getId()); // returns 0 results, wrong

        List products2 = productRepository.findAllByOwner_Id(new ObjectId(user.getId())); // returns 1 result, correct
    }
}

@Document
@Data
class User {
    @Id
    String id;
}

@Document
@Data
class Product {
    @Id
    String id;
    @DocumentReference
    User owner;
}

interface UserRepository extends MongoRepository<User, String> {

}
interface ProductRepository extends MongoRepository<Product, String> {
    List<Product> findAllByOwner_Id(String id);
    List<Product> findAllByOwner_Id(ObjectId id);
}

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions