javascript - 在 Sails.JS/Waterline 中聚合嵌套模型数据

标签 javascript node.js sails.js waterline

我正在纠结于将我的业务逻辑放在我的 SailsJS 项目中的什么位置。

我的数据模型如下:

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

我希望使用父模型上的计算属性来聚合子数据,这些数据一直级联到 Portfolio。例如, Assets 知道最新报价(价格),头寸知道其当前价格(numberShares * 其 Assets 的最新报价)等。理想情况下,我想将此数据添加到 JSON,以便我可以将业务逻辑从 Ember 客户端移开.

这在一个级别上工作正常,但如果我尝试使用子项的计算属性,它要么未定义,要么在使用 toJSON() 时为空

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;
}

这有效(在添加 typeof 检查后取决于它是否嵌套返回它不起作用)。

现在在 Position.js

 assetID:{
      model: "Asset",
    },

我想计算当前值:

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

    },

这不起作用,因为函数不可用(仅硬编码属性)。我尝试使用 Tick.Find()... 但遇到了异步问题(在获取数据之前返回 JSON)。

我试图强制嵌入/填充 JSON 中的关联,但没有任何区别。一旦我跨越一个以上的层次结构级别,我就不会获得任何数据。

我应该/可以在哪里进行聚合?我不想使用自定义 Controller 操作,而是利用 REST API。

最佳答案

Waterline 不支持深度填充。如果你想实现这样的深度查询,你可以使用 native ( https://sailsjs.com/documentation/reference/waterline-orm/models/native ) 如果你正在使用 Sails < 1,或者 manager ( https://sailsjs.com/documentation/reference/waterline-orm/datastores/manager ) 如果你正在使用 Sails >= 1

这样您就可以使用您的数据库能够构建这种“更高级”查询的任何内容。

关于javascript - 在 Sails.JS/Waterline 中聚合嵌套模型数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29340432/

相关文章:

node.js - 在代码更改时自动重新加载 Sails.js 应用程序?

javascript - 如何在 watch 模式下 sails (开发中)

javascript - 将整数改为小数而不是加或减

javascript - 在 Electron 中进行 ipc 调用时,"TypeError: Cannot read property ' 上的 ' of undefined"

javascript - 从类搜索中获取参数

html - 我的 node.js 服务器在 intelliJ 中运行,但 localhost 只提供一个空白页面

node.js - 自动向 Express 部分 View 提供数据

javascript - 向 Fluxpoint api 发送请求时出错

node.js - 处理浏览器重新加载 socket.io

javascript - 我在 Tiled 中制作的 Tile map 未在浏览器中加载