简体   繁体   中英

Sails.js Waterline query populate

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('user@acme.com').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('user@acme.com')
.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('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);
    });
  });

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('user@acme.com')
.populate('accounts', {owner: {parent: 'id'}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM