我有两个模型,ModelA和ModelB。模型B包含以下属性:

"properties": {
    "firstname": {
      "type": "string",
      "required": true
    },
    "middlename": {
      "type": "string"
    },
    "lastname": {
      "type": "string"
    }
  }

我在ModelB中创建了一个Instance方法,如下所示:

ModelB.js
'use strict';

module.exports = function(ModelB) {
  ModelB.prototype.getFullName = function() {
    console.log(this); // Display result output shown below
  }
};

I have the following result in ModelA

someTestVariable:
   { id: 'e0a844e4-6c8a-489a-8bd6-1d62267d311e',
     firstname: 'Thomas',
     middlename: '',
     lastname: 'Henry'

   }

我试图从ModelA调用ModelB中的实例方法
ModelB.prototype.getFullName();

此关键字输出以下
ModelConstructor {
  firstname: [Getter/Setter],
  middlename: [Getter/Setter],
  lastname: [Getter/Setter],
  id: [Getter/Setter],
  getFullName: [Function],
  save: [Function],
  isNewRecord: [Function],
  getConnector: [Function],
  destroy: [Function],
  delete: [Function],
  remove: [Function],
  setAttribute: [Function: setAttribute],
  updateAttribute: [Function: updateAttribute],
  setAttributes: [Function: setAttributes],
  unsetAttribute: [Function: unsetAttribute],
  replaceAttributes: [Function],
  patchAttributes: [Function],
  updateAttributes: [Function],
  reload: [Function: reload]
  }

我不确定如何从ModelA获取ModelB中的名字,中间名和姓氏数据。
任何帮助将非常感激。

最佳答案

定义原型方法如下:

ModelB.prototype.getFullName = function() {
    return this.firstname;
}

// Call instance method by creating Model instance first.

let firstNameData = new ModelB(yourObjectDataFromModelA);

// Then call prototype function

firstNameData.getFullName();

希望这能消除您的疑问。

有关更多信息,请参考以下回送文档:https://apidocs.strongloop.com/loopback-datasource-juggler/v/1.0.0/#manually-add-methods-to-the-model-constructor

07-24 09:31