'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(where{id:4});
var currentpopulation=countryp.Totalpopulation;
它给出了一个错误population.find不是一个函数。
请建议这样做的方法。
最佳答案
City.app.models.Population 只有在您定义了 City & 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
关于loopbackjs - 如何从一个持久模型的远程方法访问另一个持久环回模型的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42231014/