Question

I'm trying to follow the MongoJack tutorial but I'm failing the first task: Inserting an object into the database.

This is what I have:

DB db = new MongoClient().getDB("mydb");

JacksonDBCollection<MyDomainObject, String> coll =
    JacksonDBCollection.wrap(db.getCollection("coll"),
                             MyDomainObject.class,
                             String.class);

MyDomainObject obj = new MyDomainObject(ObjectId.get().toString(), 123456789L);

WriteResult<MyDomainObject, String> result = coll.insert(obj);

System.out.println(result.getSavedId());

Where MyDomainObject class looks as follows:

class MyDomainObject {

    // @org.mongojack.ObjectId  doesn't work
    public String id;
    public long someValue;

    public MyDomainObject(String id, long someValue) {
        this.id = id;
        this.someValue = someValue;
    }

}

With the above code I end up with the following exception:

Exception in thread "main" java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to java.lang.String
    at Test.main(Test.java:26)

And I can't for my life figure out why. Any help appreciated.

Was it helpful?

Solution

Apparently all I had to do was to rename

public String id;

to

public String _id;

(Annotating the field with @JsonProperty("_id") also seems to do the trick. AFAICT there's no way of saying that public String id should replace the _id field. If someone knows how to do this, I'm interested in how.

OTHER TIPS

You could also annotate any String field with @org.mongojack.Id. This worked for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top