13

これは腹立たしいです。ループバック モデルを取得して、プログラムで操作できるようにするにはどうすればよいですか? 「通知」という名前の永続モデルがあります。REST エクスプローラーを使用して操作できます。サーバー内でそれを操作できるようにしたい、つまり Notification.find(...)。app.models() を実行すると、リストに表示されます。私はこれをしました:

var Notification = app.models.Notification;

大きな太った「未定義」を取得します。私はこれをしました:

var Notification = loopback.Notification;
app.model(Notification);
var Notification = app.models.Notification;

そして別の大きな「未定義」。

私が定義したモデルを取得するために私がしなければならないことをすべて説明してください:

slc loopback:model

前もって感謝します

4

2 に答える 2

10

ModelCtor.app.models.OtherModelNameカスタム メソッドから他のモデルにアクセスするために使用できます。

/** common/models/product.js **/
module.exports = function(Product) {
  Product.createRandomName = function(cb) {
    var Randomizer = Product.app.models.Randomizer;
    Randomizer.createName(cb);
  }

  // this will not work as `Product.app` is not set yet
  var Randomizer = Product.app.models.Randomizer;
}

/** common/models/randomizer.js **/
module.exports = function(Randomizer) {
  Randomizer.createName = function(cb) {
    process.nextTick(function() { 
      cb(null, 'random name');
    });
  };
}

/** server/model-config.js **/
{
  "Product": {
    "dataSource": "db"
  },
  "Randomizer": {
    "dataSource": null
  }
}
于 2014-10-24T07:50:48.367 に答える
0

この投稿がずっと前にここにあったことは知っています。しかし、最近同じ質問を受けたので、最新のループバック API でわかったことは次のとおりです。

モデルが添付されたアプリケーションは、次のように取得できます。

ModelX.js

module.exports = function(ModelX) {
   //Example of disable the parent 'find' REST api, and creat a remote method called 'findA'
	var isStatic = true;
	ModelX.disableRemoteMethod('find', isStatic);

	ModelX.findA = function (filter, cb) {
      
      //Get the Application object which the model attached to, and we do what ever we want
	ModelX.getApp(function(err, app){
	  if(err) throw err;
	  //App object returned in the callback
	  app.models.OtherModel.OtherMethod({}, function(){
	  if(err) throw err;
	  //Do whatever you what with the OtherModel.OtherMethod
      //This give you the ability to access OtherModel within ModelX.
      //...
      });
     });
	}
    
   //Expose the remote method with settings.
	ModelX.remoteMethod(
	 'findA',
	 {
		description: ["Remote method instaed of parent method from the PersistedModel",
			"Can help you to impliment your own business logic"],
		http:{path: '/finda', verb: 'get'},
		  accepts: {arg:'filter', 
		  type:'object', 
		  description: 'Filter defining fields, where, include, order, offset, and limit',
		http:{source:'query'}},
			returns: {type:'array', root:true}
		}
	);
};

ここのコードブロック形式がうまくいっていないようです...

また、この「getApp」が呼び出されるタイミングにも注意する必要があります。これは、モデルの初期化時にこのメソッドを非常に早い段階で呼び出すと、「未定義」エラーのようなものが発生するためです。

于 2015-07-12T08:07:34.433 に答える