如何从一个持久模型的远程方法访问另一个持久化的环回模型的数据?

问题描述:

如何从一个持久模型的远程方法访问另一个持久化的环回模型的数据?

'use strict'; 
 
module.exports = function (City) { 
 
City.GetCurrentPopulation = function (req) { 
 
var population; 
 
City.app.models.Pupulation.find({where{id:req.id}}, //This line //gives me an error that cannot read property 'find' of undefined 
 
function(req.res){ 
 
population=res.population; 
 
}); 
 
response='Population for ' +req.cname ' is' +population; 
 
req(null, response); 
 
}; 
 
City.remoteMethod(
 
    'GetCurrentPopulation', { 
 
     http: { 
 
     path: '/GetCurrentPopulation', 
 
     verb: 'GetCurrentPopulation' 
 
     }, 
 
     returns: { 
 
     arg: 'startdate', 
 
     type: 'string' 
 
     } 
 
    } 
 
);

有一个示范城市,我想访问诸如“population.find(一些过滤器)”另一个模型如何做到这一点?

我已经写在城市模型中的远程方法。当我试图进入人口纪录

VAR countryp = population.find(其中{ID:4});

变种currentpopulation = countryp.Totalpopulation;

它给出了一个错误population.find是不是一个函数。

请建议的方式来做到这一点。如果定义市&人口模型之间的一些关系

+0

的文档是你的相关问题Loopback.js?请确保你有适合你的问题的一组标签。另外,添加关于您正在使用的环境和/或涉及的库的信息,否则很难猜测问题的内容。 –

+0

是的,它与loopback.js有关,我试图从现有的postgresql数据源创建API。 –

+0

你可以发布你的代码吗? – Dyo

City.app.models.Population才能发挥作用。否则,它不会那样工作。如果与其他模型没有关系。你需要去使用

应用程序对象的引用试试这样:

var app = require('../../server/server'); 
module.exports = function (City) { 

var Population = app.models.Population; 
City.GetCurrentPopulation = function(req) { 
    Population.find({where{id:req.id}}, function (err) { 
    if (err) { 
     return console.log(err); 
    } else { 
     // do something here 
    }); 
} 

您可以参考这里https://loopback.io/doc/en/lb3/Working-with-LoopBack-objects.html#using-model-objects

+0

谢谢你。 var app = require('../../ server/server');失踪并造成问题。 –

+0

嗨,已经以类似的方式为一个方法添加了远程挂钩。在那里,我试图访问一个模型并在其中插入一条记录。以上述方式添加了对该模型的参考。 var app = require('../../ server/server');和var Population = app.models.Population;内部导出功能。在“Population.upsert()”它说无法读取未定义的upsert。 –

+0

尝试添加var Population = app.models.Population;声明里面的函数如下 City.GetCurrentPopulation = function(req){ var Population = app.models.Population; } – Dyo