3

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.