Announcement Announcement Module
Collapse
No announcement yet.
ID field not populated when saving map Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • ID field not populated when saving map

    I have a class that extends HashMap:

    Code:
    public class CustomMap extends HashMap<String, Object> { ... }
    Now, when I save an instance of CustomMap, everything gets saved to Mongo correctly. However, if it is a new instance that does not have a _id property yet, the new _id is not being added as _id field to the CustomMap instance after the save operation. The _id is generated and persisted correctly though, it's just not being added to the CustomMap instance afterward. Here is a code snippet illustrating what I'm doing.

    Code:
    public void save(CustomMap map, String collection) {
        // assume map is: { field1: "one", field2: "two" }
        mongoOps.save(map, collection);
        // I would expect map to look like this now: { _id: ObjectId("newId"), field1: "one", field2: "two" }
        // but instead the _id field is never added
    }
    If I change the above code to convert the map to a BasicDBObject before saving it, the _id property is set correctly on the BasicDBObject instance. The problem is that the method calling save() has a reference to the CustomMap instance and I want to read the newly generated _id from it.

    Code:
    public void save(CustomMap map, String collection) {
        BasicDBObject dbObject = new BasicDBObject(map);
        mongoOps.save(dbObject, collection);
        // dbObject now has the new _id set
        // Since I want to read the generated _id from the original CustomMap object, I now need to set it:
        map.put("_id", dbObject.get("_id"));
    }
    I can work around the issue by doing the manual mapping but I was wondering if there is a better way of doing this. In particular, since I also have a similar insert(List<CustomMap>) method in which I would have to do the conversion and manual mapping for each list item.

    Maybe there is some class/interface my CustomMap could extend/implement that would allow Mongo to set the _id property?

    If possible, I would like to keep the CustomMap class generic and not in any way tight to Mongo (i.e. not extending BasicDBObject or the like).
Working...
X