Reputation: 7383
I've got two kinds of documents in my MongoDB: clients and codes. Each code refers to one client. Clients have to be stored explicitly by an administrator, therefore I have to store them separate and cannot put them into a code document.
code -> client
Now MongoDB / Morphia saves technical ids of clients as ObjectId, whereas codes refer to clients with a technical id of type String. I am able to search a code by a given client id, but at the runtime I'll get a error message, because Morphia cannot inject the client. I assume it's because of the different id types.
code { client.$id: String }
client { _id: ObjectId }
Any ideas how to fix this?
Exception
com.google.code.morphia.mapping.MappingException: The reference({ "$ref" : "clients", "$id" : "123456789abcdef" }) could not be fetched for org.example.Code.client
On the internet I found that exception message. It was suggested to use ObjectId instead of String in the model, but I have the requirement to use String. This is not my own project.
Entities:
@Entity("codes")
public class Code implements Comparable<Code> {
@Id
private String id;
@Reference
private Client client;
[...]
}
@Entity("clients")
public class Client {
@Id
private String id;
}
Storing:
To store the objects I use com.google.code.morphia.dao.DAO.save(T entity)
.
Search:
public class CodeRepository extends BasicDAO<Code, String> {
[... constructor ...]
@Override
public Code findByCode(String type, String clientId, String code) {
return findOne(createQuery()
.field("type")
.equal(type)
.field("value")
.equal(code)
.field("client")
.equal(new Key<Client>(Client.class, clientId)));
}
}
Upvotes: 4
Views: 5351
Reputation: 29
I did it slightly differently so i could use the id as path param in REST requests.
@Id
private String id = new ObjectId().toHexString();
Upvotes: 1
Reputation: 1404
not sure if this is solved yet. I had the same problem. The solution for me was to set the id myself.
@Id
private String id = new ObjectId().toString();
Now you can treat the id field like any other string field.
Hope this helps.
Upvotes: 6