Search code examples
javamongodbmorphiaspark-framework

Update mongo object using body content


so i know i need to query the user by uuid and then update the user but im having troubles in how to do that, this is my current code. Im currently using morphia and spark-framework.

import eu.unionmc.api.model.User;
import eu.unionmc.api.service.dao.UserDAO;
import eu.unionmc.api.utils.DatabaseHandler;

import java.util.List;

public class UserService {

private DatabaseHandler dbHandler = new DatabaseHandler();
private UserDAO userDAO = dbHandler.getUserDAO();

public String addUser(User user){
    userDAO.save(user);
    return "add user";
}

public List<User> getAllUsers(){
    return userDAO.find().asList();
}

public User getByUsername(String username){
    return userDAO.findOne("username", username);
}

public User getByUUID(String uuid){
    return userDAO.findOne("uuid", uuid);
}

public String update(String uuid, String body){
    return "Not found";
}

}

I've been searching but no one is using morphia only mongodb which i've tried but failed.

User routes:

public class UserRoutes implements ExportRoute {

private UserService userService = new ServiceFactory().getUserService();

@Override
public void export() {
    Gson gson = new Gson();
    String apiPath = "/api/";

    /*
     * Return all users in a JSON format
     */
    get(apiPath + "users", (req, res) -> {
        res.type("application/json");
        return userService.getAllUsers();
    }, gson::toJson);

    /*
     * Return a user match with params username
     */
    get(apiPath + "users/:username", (req, res) -> {
        res.type("application/json");
        User user = userService.getByUsername(req.params("username"));

        if(user != null){
            return user;
        }else {
            return "User not found";
        }

    }, gson::toJson);

    get(apiPath + "users/uuid/:uuid", (req, res) -> {
        res.type("application/json");
        User user = userService.getByUUID(req.params("uuid"));

        if(user != null){
            return user;
        }else {
            return "User not found";
        }

    }, gson::toJson);


    /*
     * Create a new user using a json body format
     */
    post(apiPath + "users", (req, res) -> {
        res.type("application/json");
        User user = gson.fromJson(req.body(), User.class);
        return userService.addUser(user);
    }, gson::toJson);

    //Update existing user by uuid
    put(apiPath + "users/:uuid", (req, res) -> {
        res.type("application/json");
        return "Do something to update";
    }, gson::toJson);
}
}

User class: Just a class POJO

   package eu.unionmc.api.model;

    import org.bson.types.ObjectId;
    import org.mongodb.morphia.annotations.Entity;
    import org.mongodb.morphia.annotations.Id;
    import org.mongodb.morphia.annotations.IndexOptions;
    import org.mongodb.morphia.annotations.Indexed;

    import java.util.UUID;

    @Entity(value = "users", noClassnameStored = true)
    public class User {

    @Id
    private ObjectId id;

    @Indexed(options = @IndexOptions(unique = true))
    private String uuid;

    private String username;
    private long coins, tokens;

    public User() {
    }

    public ObjectId getId() {
        return id;
    }

    public String getUUID() {
        return uuid;
    }

    public void setUUID(UUID uuid) {
        this.uuid = uuid.toString();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public long getCoins() {
        return coins;
    }

    public void setCoins(long coins) {
        this.coins = coins;
    }

    public long getTokens() {
        return tokens;
    }

    public void setTokens(long tokens) {
        this.tokens = tokens;
    }
}

Solution

  • In your DAO you need access to morphia's Datastore Object and then you can perform the following query:

    public class UserDao{
    
    // ... your configs, you need to have a Datastore object available here
    
    public void findByUuidAndUpdate(String uuid, String newValue){
       query = datastore.createQuery(User.class).field("uuid").equal(uuid);
       ops = datastore.createUpdateOperations(User.class).set("fieldToUpdate", 
    newValue);
    
        datastore.update(query, ops);
      }
    }