If you find by id, and the identifier is provided by the user (meaning that it can be any type of data), you should not use the solutions above.
As explained in the documentation , ObjectId consists of 12 bytes, so if you pass something else to new ObjectId(myValue), your code will throw a IllegalArgumentException.
This is how I implemented the method for searching by id:
public Model findById(String id) throws NotFoundException {
if (!ObjectId.isValid(id)) {
throw new NotFoundException();
}
ObjectId oid = new ObjectId(id);
Model m = datastore().find(Model.class).field("_id").equal(oid).get();
if (m == null) {
throw new NotFoundException();
}
return m;
}
source
share