Search code examples
javaspringmongodbspring-bootspring-mongodb

MongoDB spring application getAll request not returning all fields


I have created a spring boot application needed for querying and posting to a MongoDB database, I have created a data model that is to be submitted from a website, as well as a service to auto increment document ids, and created routes needed to make requests to and from the application. My issue is when I attempt to query all documents in my gallery table it only returns the ids and not all of the fields in my collection. As well as my route to query one document only returns 404 codes now. It was working before properly but since I've added onto it the bug started happening.

expected output:
[
{
"id":1,
"title":"test",
"imageURL":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwM...",
"datePosted":"9/4/2022",
}
]

what I am getting:
[
  {
    "id": 1
  }
]

Model:

package com.v0ncent.server.POJOMODELS;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
@Document("gallery")
public class Gallery { //DO NOT CONVERT THIS TO A RECORD IT WILL FUCK THE APP!!!!!
    @Id
    private long id;
    //
    final String title,imageURL,datePosted;
    @Transient
    public static final String SEQUENCE_NAME="gallery_sequence"; // to auto increment documents we need to define this documents specific sequence
    public Gallery(long id, String title, String imageURL, String datePosted){
        super();
        this.id = id;
        this.title = title;
        this.imageURL = imageURL;
        this.datePosted = datePosted;
    }
    //getters for object
    /**
     * @return returns id of Object instance.
     * */
    public long getId(){
        return id;
    }
    //setters for object
    /**
     * Sets the current object Instance id.
     * @param id updated id
     * */
    public void setId(int id){
        this.id = id;
    }
}

Sequence model:

package com.v0ncent.server.POJOMODELS;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document("db_sequence")
@Data
@AllArgsConstructor
@NoArgsConstructor
public final class DBSequence {
    @Id
    private String id;
    private int seq; //sequence
    /**
     * getter for Sequence integer of object instance
     * @return returns the current sequence of object instance
     * */
    public int getSeq() {
        return seq;
    }
}

GalleryRepository for gallery model

package com.v0ncent.server.Repository;
import com.v0ncent.server.POJOMODELS.Gallery;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface GalleryRepository extends MongoRepository<Gallery,String> {
    /**
     * Finds one document from gallery DB.
     * @param id id of document to be found in gallery DB.
     * */
    @Query("{_id:'?0'}")
    Gallery findOne(long id);
    //
    long count();
}

Services:

package com.v0ncent.server.Mongo;
import com.v0ncent.server.POJOMODELS.DBSequence;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.data.mongodb.core.query.Query;
import java.util.Objects;
import static org.springframework.data.mongodb.core.FindAndModifyOptions.options;
@Service
public class SequenceGeneratorService {
    private final MongoOperations mongoOperations; 
    public SequenceGeneratorService(MongoOperations mongoOperations){
        this.mongoOperations = mongoOperations;
    }
    /**
     * Gets the current sequence number for given sequence name.
     * @param sequenceName name of table sequence to get sequence of (number of documents basically)
     * @return returns the sequence number increased by one for auto incrementing purposes
     * */
    public int getSequence(String sequenceName){
        //get sequence number
        Query query = new Query(Criteria.where("id").is(sequenceName));
        //update sequence number
        Update update = new Update().inc("seq",1);
        //modify in document
        DBSequence counter = mongoOperations
                .findAndModify(query, update,
                        options().returnNew(true).upsert(true),
                        DBSequence.class);
        // ! and ? is basically if then statement, if object isn't null increase counter by 1
        return !Objects.isNull(counter) ? counter.getSeq() : 1;
    }
}
package com.v0ncent.server.Mongo;
import com.mongodb.lang.NonNull;
import com.v0ncent.server.C;
import com.v0ncent.server.POJOMODELS.Gallery;
import com.v0ncent.server.Repository.GalleryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Optional;
@Service
public class GalleryTool{
    @Autowired
    private GalleryRepository galleryRepository; 
    /**
     * Method for querying all documents in gallery DB.
     * @return returns all documents in the Gallery as a collection. If error returns null.
     * @see GalleryRepository
     * */
    public Collection<Gallery> getAll() {
        try {
            return this.galleryRepository.findAll();
        } catch (Exception e){
            C.EXCEPTION_MANAGER.handle(e,GalleryTool.class);
        }
        return null;
    }
    /**
     * Saves listing to gallery DB.
     * @param gallery Object to be saved to gallery database. {cannot be null!}
     * @return returns the saved gallery object from request body. If error returns null.
     * */
    public Gallery createListing(@NonNull Gallery gallery) {
        try{
            this.galleryRepository.save(gallery);
            return gallery;
        }catch (Exception e){
            C.EXCEPTION_MANAGER.handle(e,GalleryTool.class);
        }
        return null;
    }
    /**
     * Queries one document from gallery DB. {cannot be null!}
     * @param id id of document to query.
     * @return returns an optional of a Gallery Object if it is listed in gallery DB.
     * */
    public Optional<Gallery> getOne(@NonNull long id) {
        try {
            return Optional.ofNullable(galleryRepository.findOne(id));
        }catch (Exception e){
            C.EXCEPTION_MANAGER.handle(e,GalleryTool.class);
        }
        return Optional.empty();
    }
    /**
     * Updates one listing in gallery DB. {cannot be null!}
     * @param gallery Gallery object to be updated within gallery DB.
     * @return returns the updated Gallery Object. Returns null if error.
     * */
    public Gallery updateOne(@NonNull Gallery gallery){
        try{
            galleryRepository.save(
                    gallery
            );
            return gallery;
        }catch (Exception e){
            C.EXCEPTION_MANAGER.handle(e,GalleryTool.class);
        }
        return null;
    }
    /**
     * Deletes one listing from gallery DB.
     * @param id id of document to be deleted from gallery DB.
     * */
    public void deleteOne(@NonNull long id){
        galleryRepository.deleteById(String.valueOf(id));
    }
}

Controller

package com.v0ncent.server.Routes;
//
import com.mongodb.lang.NonNull;
import com.v0ncent.server.Mongo.GalleryTool;
import com.v0ncent.server.Mongo.SequenceGeneratorService;
import com.v0ncent.server.POJOMODELS.Gallery;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Optional;
//TODO: FIX THIS SHIT
@RestController
@RequestMapping("/api")
public class GalleryController {
    private static final Logger LOGGER = LoggerFactory.getLogger(GalleryController.class);
    @Autowired 
    private GalleryTool galleryTool;
    @Autowired
    private SequenceGeneratorService service; 
    //
    @GetMapping("/getAllGallery")
    Collection<Gallery> getAllGallery(){
        return galleryTool.getAll();
    }
    //
    @GetMapping("/getOneGallery/{id}")
    ResponseEntity<?> getOneGallery(@NonNull @PathVariable Long id){
        Optional<Gallery> galleryOptional = galleryTool.getOne(id);
        return galleryOptional.map(response -> ResponseEntity.ok().body(response))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
    //
    @PostMapping("/createListingGallery")
    ResponseEntity<Gallery> createListingGallery(@Valid @RequestBody Gallery gallery) throws URISyntaxException {
        LOGGER.info("Request to create new GALLERY Listing: {}",gallery);
        gallery.setId(service.getSequence(Gallery.SEQUENCE_NAME)); 
        Gallery result = galleryTool.createListing(gallery);
        return ResponseEntity.created(new URI("/api/createListingGallery" + result.getId())).body(result);
    }
    @PutMapping("/updateOneGallery/{id}")
    ResponseEntity<Gallery> updateOneGallery(@Valid @RequestBody Gallery gallery){
        LOGGER.info("Request to update GALLERY Listing: {}",gallery);
        Gallery result = galleryTool.updateOne(gallery);
        return ResponseEntity.ok().body(result);
    }
    @DeleteMapping("/deleteOneGallery/{id}")
    ResponseEntity<?> deleteOneGallery(@PathVariable Long id){
        galleryTool.deleteOne(id);
        return ResponseEntity.ok().build();
    }
}

I have tried removing my new sequencing service and running query routes again but the same bug occurred, I have tried creating a new DB and table, and have tried updating my application.properties with a new MongoDB user.

So with that I have come to a standstill and have not been able to find anything online similar to this issue, any help would be appreciated.


Solution

  • I fixed it by adding getters to the Gallery model,

    package com.v0ncent.server.POJOMODELS;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.annotation.Transient;
    import org.springframework.data.mongodb.core.mapping.Document;
    @Document("gallery")
    public class Gallery { //DO NOT CONVERT THIS TO A RECORD IT WILL FUCK THE APP!!!!!
        @Id
        private long id;
        //
        final String title,imageURL,datePosted;
        @Transient
        public static final String SEQUENCE_NAME="gallery_sequence"; // to auto increment documents we need to define this documents specific sequence
        public Gallery(long id, String title, String imageURL, String datePosted){
            super();
            this.id = id;
            this.title = title;
            this.imageURL = imageURL;
            this.datePosted = datePosted;
        }
        //getters for object
        /**
         * @return returns id of Object instance.
         * */
        public long getId(){
            return id;
        }
        public String getTitle(){
            return title;
        }
        public String getImageURL(){
            return imageURL;
        }
        public String getDatePosted(){
            return datePosted;
        }
        //setters for object
        /**
         * Sets the current object Instance id.
         * @param id updated id
         * */
        public void setId(int id){
            this.id = id;
        }
    }