gradecam / mongoose-decorators-ts

TypeScript decorators for Mongoose models.
MIT License
15 stars 0 forks source link

is this lib possible for object fields? #5

Open zhaochy1990 opened 4 years ago

zhaochy1990 commented 4 years ago

suppose I have a mongoose model like the following, how can I use this lib to modeling the address and metadata fields?

const { Schema } = mongoose;

const user = new Schema ({
  address: {
      country: {
         type: String
      },
     province: {
        type: String
     },
     street: {
       type: String
     }
  },
  metadata: {
    type: Object,
    default: {}
  }
});
taxilian commented 4 years ago

Absolutely. mongoose-decorators-ts is just a wrapper around the Schema which intuits information from an object, so literally anything you can do without it you can do with it -- just a question of how "clean" it will be. In this case it is very easy, since Object is the same as Mixed and the abstraction will treat any as a Mixed type. Any interface which it can't map to a javascript type will be reported as any by the typescript decorators, so you can just make your own interface for it.

interface MetadataObject {
    [key: string]: string | number | boolean;
}

@schemaDef()
class AddressSchema() {
    @field() country: string;
    @field() province: string;
    @field() street: string;
}

@schemaDef()
class UserSchema {
    @field() address: AddressSchema;
    @field() metadata: MetadataObject;
}

Note that you could also pass in type as an option and explicitely set the type, like so:

@field({type: Object}) metadata: MetadataObject;