5

After upgrading to spring data mongodb 1.10.1, I am getting errors when running queries like:

@Query("{$and :["
            + "{ $or : [ { $where: '?0 == null' } , { 'field1' : ?0 } ] },"
            + "{ $or : [ { $where: '?1 == null' } , { 'field2' : ?1 } ] },"
            + "]}")
public Page<Entity> findAll(String param1, String param2)

Checking the error I see the parameter inside the where clause is not quoted and as I result I get:

org.springframework.data.mongodb.UncategorizedMongoDbException: Query failed with error code 139 and error message 'ReferenceError: test_param_value is not defined :

I have seen a few answers here recommending this way of handling optional parameters ((spring-data-mongo - optional query parameters?)) but it no longer works and I cannot seem to find anything in the release change log.

Community
  • 1
  • 1
jsc
  • 143
  • 1
  • 8
  • it does not know what type is ?0 or ?1, it can't compare undefined == null because it can't figure out what is undefined. Hope it makes sense. – Euclides Apr 06 '17 at 15:30

1 Answers1

8

In case anyone else is interested, I managed to find a workaround after checking a similar ticket int the Spring Data project.

It seems the way I was checking for null parameters in the query is not a good practice. This is from a Spring developer comment: "placeholders are not designed to compose keys/values but bind parameters. Beyond that, placeholder use in quoted strings is always problematic in terms of escaping. Using SpEL should suit your needs"

So I ended up using SpEL to do the checks on parameters and it works fine. This is how it looks:

@Query("{$and :[" 
        + "?#{ [0] == null ? { $where : 'true'} : { 'field1' : [0] } },"
        + "?#{ [1] == null ? { $where : 'true'} : { 'field2' : [1] } },"
        + "]}")
public Page<Entity> findAll(String param1, String param2, Pageable pageable);
jsc
  • 143
  • 1
  • 8