mean-expert-official / loopback-sdk-builder

Tool for auto-generating Software Development Kits (SDKs) for LoopBack
Other
399 stars 175 forks source link

Validation issue with DEFAULT USER ID = 0 -- Should be null [ mongoDB ] #502

Open luncht1me opened 7 years ago

luncht1me commented 7 years ago

There's a poor convention in the loopback-sdk-builder for angular2 that's been stumbled upon starting a new project.

Using fireloop, and mongoDB as our datasource for loopback models.

The loopback-sdk-builder is generating new Users with an id = 0; This fails loopback validation when creating a new instance and persisting it to the database w/ mongoDB, as you cannot set ID. This is a pretty fatal flaw for a newbie looking to simply follow the example documentation on getting started as they'll be stopped by an internal validation error while trying to upsert their first new user.

Take this following Component:

export class RootComponent {
  private user: User = new User({username: "foo", email: "foo@bar.com",password:"bar"});
  private UserReference: FireLoopRef<User>;

  constructor(private realTime: RealTime) {
    this.realTime.onReady().subscribe(() => { this.UserReference = this.realTime.FireLoop.ref<User>(User) });
  }
  private create(): void {
   // need to set `this.user.id = null` for this upsert to not fail validation "id cannot be set"!
    this.UserReference.upsert(this.user).subscribe((user: User) => {console.log(user)});
  }
}

What's happening, is when loopback cannot find a user of id 0, it tries to create one, but with the payload of id:0 - Which then triggers the validation error "cannot set id".

User IDs should not have a default value when being instantiated for the first time. You're always supposed to let the database set your id automatically on generating a new document (mongoDB).

jonathan-casarrubias commented 7 years ago

@luncht1me thanks for reaching out,

Hey so... By default the SDK won't generate any default value, nor an ID. There is an option though, that enables default values for models properties, this option actually has to be enabled, so it is possible you did that.

If you don't want default values to be created, then disable that option when generating the SDK.

Anyway, if you require to set defaults enabled because other atributes, well then you have 2 options.

A) set ID to null, B) add a PR to modify id defaults.

Default values is a community contribution so technically I have never even used that feature, so if you think it can be improved, maybe a PR is the best option.

Cheers Jon