Ganesh Mahajan
Ganesh Mahajan

Reputation: 83

How to access data of another persisted model of loopback from remote method of one persisted model?

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

There is a model city and i want to access another model like "population.find(some filters)" How to do this?

I have a remote method written in city model. Where i am trying to access population record as

var countryp=population.find(where{id:4});

var currentpopulation=countryp.Totalpopulation;

It gives an error population.find is not a function.

Please suggest way to do this.

Upvotes: 3

Views: 5742

Answers (1)

Mew
Mew

Reputation: 1152

City.app.models.Population can only work if you defined some relation between City & Population models. Otherwise it wont work that way. If there is no relation to the other model. You need to get a reference to the app object using

Try like this:

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

You can refer to the documentation here https://loopback.io/doc/en/lb3/Working-with-LoopBack-objects.html#using-model-objects

Upvotes: 9

Related Questions