Search code examples
loopbackjsstronglooploopback

How to call remote method of one persisted model inside another remote method of another persisted model


here's what I tried in model1.js:

      model1.remotemethod1 = function(id, data, cb) {
var model2 = app.models.model2;
model2.remotemethod2(id, data).then(response => {
cb(null, true);
});
 };

this is my model2.js : it has the definition of remotemethod2 .

 'use strict';

  module.exports = function(model2) {

  model2.remotemethod2 = function(id, data, cb) {
     var promise;
     let tags = data.tags ? data.tags.slice() : [];
     delete data.categories;
     delete data.tags;
     promise = model2.upsertWithWhere({
             or: [
                 {barcode: data.barcode},
                 {id: data.id},
             ],
         }, data);
     promise.then(function(model2) {
         model2.tags.destroyAll().then(function() {
             for (let i = 0; i < tags.length; i++) {
                 model2.tags.add(tags[i]);
             }
             cb(null, model2);
         });
     });
    };
 };

But it dos not work ! I think that app.models.model2 does not give me the model with its remote methods ! maybe I should get an instance of the model2 !


Solution

  • var (VAR-NAME)= (CURRENT-MODEL).app.models.(ANOTHER_MODEL);
    

    you now can use the other model by calling one of its methods for example

    EX:

    VAR-NAME.create();