简体   繁体   中英

Aggregate nested model data in Sails.JS/Waterline

I'm struggling with where to put my business logic in my SailsJS project.

My data model is as follows:

Portfolio (hasMany) -> Positions (hasOne) -> Asset-> (hasMany) Ticks 

I'm looking to aggregate data of the children using computed properties on the parent model cascading all the way up to Portfolio. eG an Asset knows the newest tick (price), the position knows its current price (numberShares * newest Tick of its Asset), etc. Ideally i want to add this data to the JSON so i can move business logic away from the Ember client.

This works fine for one level, but if i try to use a computed property of a child, it's either non defined or when using toJSON() empty

Asset.js:

latestTick: function () {
    if (this.ticks.length> 0) 
    {

      this.ticks.sort(function(a, b){
       var dateA=new Date(a.date), dateB=new Date(b.date)
       return dateB-dateA
      })


      return this.ticks[Object.keys(this.ticks)[0]].price;
    }

    return 0;
  },


  toJSON: function() {
    var obj = this.toObject();


  if (typeof this.latestTick === 'function')
    obj.latestTick = this.latestTick();
  return obj;
}

This works (after adding the typeof check as depending on whether it was returned nested or not it didn't work).

Now in Position.js

 assetID:{
      model: "Asset",
    },

i want to calculate currentValue:

   currentValue: function () {
         return this.assetID.latestTick() * this.numberShares;

    },

which does not work because the function is not available (only the hardcoded attributes). I tried using Tick.Find()... but ran into async issues (JSON is returned before data is fetched).

I tried to force embedding / populate the associations in the JSON but it made no difference. As soon as I'm crossing more than one hierarchy level i don't get any data.

Where should/can i do this aggregation? I don't want to use custom controller actions but leverage the REST API.

Waterline does not support deep populates. If you want to implement a deep query like that, you can use native ( https://sailsjs.com/documentation/reference/waterline-orm/models/native ) if you are using Sails < 1, or manager ( https://sailsjs.com/documentation/reference/waterline-orm/datastores/manager ) if you are using Sails >= 1

That way you can use whatever your database is capable for building this kind of "more advanced" queries.

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