Skip to content
Advertisement

Can’t modify @Embedded List in Morphia

I have the following Entity:

@Entity("users")
public class UserModel {
   @Id
   private ObjectId id;
   private String userID;
   private String prefix;
   private List<TodoList> todoLists;
   private List<Reminder> reminders;

The TodoList Object looks like this:

@Embedded
public class TodoList {
    private String name;
    private List<String> todos;
    private List<String> completed;

What I’m trying to do is to move a String from the todos ArrayList to the completed ArrayList inside a TodoList, here is how I’m trying to do that:

public void completeTodo(int listIndex, int todoIndex, UserModel userData) {
    String todo = userData.getTodoLists().get(listIndex).getTodos().remove(todoIndex);

    datastore.find(UserModel.class)
        .filter(Filters.eq("userID", userData.getId()))
        .update(UpdateOperators.set("todoLists." + listIndex + ".todos", userData.getTodoLists().get(listIndex).getTodos()), UpdateOperators.push("todoLists." + listIndex + ".completed", todo))
        .execute();
}

This doesn’t do anything and I have no clue of what could be wrong. Also, if I simply modify the full TodoList, moving the todo from the todos ArrayList to the completed ArrayList, and then using the set UpdateOperator like so:

public void completeTodo(int listIndex, int todoIndex, UserModel userData) {
    userData.getTodoLists().get(listIndex).completeTodo(todoIndex);

    datastore.find(UserModel.class)
        .filter(Filters.eq("userID", userData.getId()))
        .update(UpdateOperators.set("todoLists." + listIndex, userData.getTodoLists().get(listIndex)))
        .execute();
}

It still doesn’t work, even thought I logged the todo variable and the userData and it all looks correct, I just can’t manage to save it into the DB.

I also tried this:

public void completeTodo(int listIndex, int todoIndex, UserModel userData) {
    String todo = userData.getTodoLists().get(listIndex).removeTodo(todoIndex);
    System.out.println(todo); // This logs correctly, so at least the push operator should work

    datastore.find(UserModel.class)
        .filter(Filters.eq("userID", userData.getId()))
        .update(UpdateOperators.set("todoLists." + listIndex + ".todos", userData.getTodoLists().get(listIndex).getTodos()), UpdateOperators.push("todoLists." + listIndex + ".completed", todo))
        .execute();
}

where removeTodo is (inside the TodoList Embedded class):

public String removeTodo(int todoIndex) {
    return todos.remove(todoIndex);
}

Advertisement

Answer

Well I should have checked my code twice. It appears that userData.getId() wasn’t the right ID of the user in the database :/

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement