dresende / node-orm2

Object Relational Mapping
http://github.com/dresende/node-orm2
MIT License
3.07k stars 379 forks source link

Default association values making it hard to debug #710

Open nallown opened 8 years ago

nallown commented 8 years ago

By default when creating a association and the second model hasn't been defined, the association gets created with it self which make it hard to debug the problem.

Take the following as a example:

  const User = db.define('user', {
    username         : { type: 'text', required: true, unique: true },
    email            : { type: 'text', required: true, unique: true },
    password         : { type: 'text', required: true },
    created_at       : { type: 'date', required: true, time: true }
  });

  User.hasMany('ips', undefined, {}, {reverse: 'user', key: true});

Since the User Ip associations is set to undefined here, it instead sets the User Ip association to be with it self (User).

Looks like that the reason to why this happens is this: https://github.com/dresende/node-orm2/blob/master/lib/Associations/One.js#L12 https://github.com/dresende/node-orm2/blob/master/lib/Associations/Many.js#L12

It would be good if it could throw some kind of error when the association fails to create with required attributes instead of associating it with defaults.

A scenario where this might go wrong is with automating the loading of the models from a directory. The way that I encountered this problem was that the Models get automatically loaded from a directory and the Model files them selves have the associations inside of them as well.

tl;dr: Remove defaults from associations and throw error if required attributes are missing.