Search code examples
mongodbangulartypescriptmappingbson

BSON ObjectID (Morphia) representation in Typescript/Angular2 Project


I have a Java class representing a customer with some properties like name, adress etc. And I have the property:

@Id
@Property("_id")
private ObjectId id;

The customer will be fetched from a mongoDB. Everything is fine and all properties are filled. Then I try to transport data via REST to a angular2 client I have a Customer representation in typescript

export class Customer {
    public id: string <---

Mapping inside rest call in client

.map((response: Response) => <Customer> response.json()) 

what do I need to put here, that the property will be mapped and that I can use it within the angular client. I've tried to install bson-objectid via npm, but I have no idea how to get it to map the id property. All the others are working fine.


Solution

  • Solution found! Create a

    public YourAdapterName extends XMLAdapter<String, ObjectID> {
       @Override
       public String marshal(ObjectId v) throws Exception {
           return v.toString();
       }
    
       @Override
       public ObjectId unmarshal(String v) throws Exception {
           return new ObjectId(v);
       }
    }
    

    This Adapter returns the string representation of the ObjectID and I can use

    id: string 
    

    in Typescript.