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

标签 loopbackjs strongloop loopback

'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/

相关文章:

Strongloop:currentContext 在中间件中不可用?

javascript - 环回模型在保存之前删除属性或属性

mysql - 尝试将数据 GET 或 POST 到 mySQL 数据库时,LOOPBACK 中出现错误。我在这里缺少什么?

android - Android 蓝牙中的环回

javascript - 如何仅向环回 API socket.io 中连接的套接字(客户端)发送数据

express - 使用第 3 方登录的 Auth0 LoopbackJS API 访问 token

model - 如何从 LoopBack 模型中读取查询过滤器

node.js - 有很多关系 : including from the other direction

javascript - Loopback - 包括关系的计算属性

javascript - 如何使用 .push 保存数组以在 .map() 之外异步读取?