'Mongo Spring Boot not finding user with indexed name

This is my user document

@Document("user")
public class User {

    @Id
    @Field("_id")
    private String id;
    
    @Indexed
    private String name;
    private String password;
    
    User() {
    }

    public User(String name, String password) {
    this.name = name;
    this.password = password;
    }

    public String getId() {
    return id;
    }

    public String getName() {
    return name;
    }

    public String getPassword() {
    return password;
    }
}

This is what it looks like in mongodb enter image description here

But for some reason when I use this code

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) {
    System.out.println("Searching for user: " + username);

    User user = userRepository.findByName(username);
    //Does not reach code below this point
    System.out.println("Search finished");
    
    if (user == null) {
        System.out.println("Aborted. User not found");
        throw new UsernameNotFoundException(username);
    }

    System.out.println("User found. Password: " + user.getPassword());

    return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(),
        grantedAuthorities);
    }

It prints out "Searching for user: Name" but does not print out "search finished" or "user found". My user repository looks like this

@Repository
public interface UserRepository extends MongoRepository<User, String> {

    @Query("{'name': ?0}")
    User findByName(String name);
}

So my question is: Why is it getting stuck on userRepository and how do I fix it. No errors are printed to the console or anything, it just doesn't work.



Solution 1:[1]

Since you are using MongoRepository, you don't have to specify the @Query annotation, leave it for complex queries. Also you don't have to specify @Field("_id") for the id since you already added the @Id to the attribute, so it will do the same.

Could you now try to correct your repository like that and tell me if it works:

    @Repository
    public interface UserRepository extends MongoRepository<User, String> {
    
       Optional<User> findByName(String name);
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ExtraHassan