I\'m currently using Spring Boot to create a REST API with a mongodb backend. Is it possible to only expose certain fields when viewing a specific item, and not a list of it
When using Spring Data REST it has something especially designed for this. There is the notion of Projections and Excerpts with it you can specify what and how you want to return it.
First you would create an interface which would contain only the fields you want.
@Projection(name="personSummary", types={Person.class})
public interface PersonSummary {
String getEmail();
String getId();
String getName();
}
Then on your PersonRepository
add this as the default to use (will only apply to methods returning collections!).
@RepositoryRestResource(excerptProjection = PersonSummary.class)
public interface PersonRepository extends CrudRepository<Person, String> {}
Then when doing a query for a collection you will only get the fields as specified in the projection and when obtaining a single instance you will get the full object.
You have to add @Query
annotation on the find method in the repository and specify the fields
parameter:
public interface PersonRepository extends MongoRepository<Person, String>
@Query(value="{ 'firstname' : ?0 }", fields="{ 'firstname' : 1, 'lastname' : 1}")
List<Person> findByThePersonsFirstname(String firstname);
}
See: http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongodb.repositories.queries.json-based