wjentner
wjentner

Reputation: 535

MongoRepository findOne using "id" instead of "_id"

I have a setup very similar to this one: http://spring.io/guides/gs/accessing-data-mongodb/

In my POJO class I use a String field (annotated with @Id) and set it manually.

public class MyPojo {
  @Id
  private String id

  public MyPojo(String id) {
    this.id = id
  }

  //...
}

Like in the example I use an extended interface of MongoRepository:

public interface MyPojoRepository extends MongoRepository<MyPojo, String> {

}

When I save my object

myrepo.save(new MyPojo("user"));

Everything works fine and in my collection _id = "user" as I expect it to be.

However, if I want to query that object now:

myrepo.findOne("user")

I receive null. The debug log shows that my collection is queried with

{ "id" : "user" }

instead of "_id". Is this behavior intended? I find this very confusing. Especially because the JavaDoc explicitly mentions the term "id" here.

//EDIT:

myrepo.exists("user") 

returns true...

Upvotes: 3

Views: 10967

Answers (2)

Rotem
Rotem

Reputation: 1379

The ability to change the field name saved in the MongoDB is by using the following annotation: import org.springframework.data.mongodb.core.mapping.Field

by using the annotation you can define the field name in the mongoDB.

For example:

@Field("email")
private EmailAddress emailAddress;

Now emailAddress will be saved in the database using the key email.

The mongoDB will always use the _id as one of the document's unique identifier.

In the case you have you can make another field calls userId, which can be duplication of the _id field but with the syntax you like, such as:

@Field("id")
private String userId;

I hope that helps.

Upvotes: 3

Ely
Ely

Reputation: 11152

Don't use the constructor

 public MyPojo(String id) {
   this.id = id
 }

because you must not assign the id manually.

MongoDB uses this field internally and you are about to put a string into an ObjectID field type.

Simply provide an empty constructor and/or constructor that initialize fields that are part of the document (that is field of type String for user.

In the link of your guide you have a good example!

Upvotes: 0

Related Questions