Given that a user can have many accounts and an account can have many users, with an account always having an owner. Is there a better way to write this in Waterline query syntax?
User.findOneByEmailAddress('[email protected]').then(function(user) {
User.findOne(user.id)
.populate('accounts', {owner: user.id})
.then(console.log);
});
I guess I would prefer something like this, if possible:
User.findOneByEmailAddress('[email protected]')
.populate('accounts', {owner: this.id})
.then(console.log);
While in this case I think a double query must always occur, but it would sure make the code easier to read if the populate() could reference the calling party ID.
I understand this example is a bit contrived.
I also tried this:
User.findOneByEmailAddress('[email protected]').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);
});
});
It took me a few minutes to figure out what you were after, and sadly the answer is no, there's currently no way to access the result of a "parent" query in the populate
criteria. It's an interesting idea that you should consider posting to Github as a feature request. Using this
wouldn't work, it but it could be something like:
User.findOneByEmailAddress('[email protected]')
.populate('accounts', {owner: {parent: 'id'}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With