sylvainpolletvillard / ObjectModel

Strong Dynamically Typed Object Modeling for JavaScript
http://objectmodel.js.org
MIT License
467 stars 28 forks source link

Default for Nested Models #159

Closed lafama closed 1 year ago

lafama commented 1 year ago

Is it possible to do the following

let Place=new ObjectModel({
    id:ObjectId,
    name:String
}).defaultTo({
  id:new ObjectId()
});

let Country=new ObjectModel({
  id:ObjectId,
  name:String,
  city:Place,
adminLocations:[ArrayModel(Place)]
}).defaultTo({
  id:new ObjectId()
})

So if the city/adminLocations is provided and the id is missing it's always set to the id value. What am trying to do it to replace the mongoosejs _id autogeneration logic for schema definition

let x=County({name:'Country Name',city:{name:'city'}, adminLocations:[{name:"location one"}] })

would result in {name:"Country Name",id:"948783728947328", city:{name:"city",id:"938372897389"},adminLocations:[{name:"location one",id:"3928903290382"}]}

Thank you

sylvainpolletvillard commented 1 year ago

Hi,

That's not really a default value, since it will change for every object. What you're looking for is an instanciation logic, which can be declared in a class constructor or a factory function:

const Place=new ObjectModel({
    id:ObjectId,
    name:String
})

function createPlace(name){
  return new Place({ name, id: ObjectId() })
}

or

class Place extends ObjectModel({ id: ObjectId, name: String }) {
  constructor(name){
     super({ id: ObjectId(), name })
  }
}

If you're looking for a library to generate unique identifiers, I suggest https://www.npmjs.com/package/nanoid