Given that a user can have many accounts, and an account can have many users, the account always has an owner. Is there a better way to write this in the Waterline query syntax?
User.findOneByEmailAddress(' user@acme.com ').then(function(user) { User.findOne(user.id) .populate('accounts', {owner: user.id}) .then(console.log); });
I think I would prefer something like this:
User.findOneByEmailAddress(' user@acme.com ') .populate('accounts', {owner: this.id}) .then(console.log);
While in this case I think that a double query should always take place, but it will undoubtedly make the code easier to read if populate () can refer to the caller ID.
I understand that this example is a bit contrived.
I also tried this:
User.findOneByEmailAddress(' user@acme.com ').then(function(user) { user.isAccountOwner().then(console.log); });
In my model, I defined an instance method:
isAccountOwner: function() { var _this = this; return new Promise(function(resolve, reject) { User.findOne(_this.id) .populate('accounts', {owner: _this.id}) .then(function(user) { resolve(!! user.accounts.length > 0); }) .fail(function(err) { reject(err); }); });
source share