在Loopback文档Initializing the application中,说了两件事:
首先:
然后 :
两者似乎不是矛盾的吗?
我有很多要定义的模型,我不想在一个巨大的json
文件中定义,因此要在启动时加载每个js
目录中的每个模型一个models/
文件。
目前,我所做的是在models/ExampleModel.js
中定义一个模型,如下所示:
var properties = {
fieldOne: { type: String, required: true },
otherField: { type: Number }
};
var options = {
relations: {
collections: {
type: "belongsTo",
model: "user"
}
}
};
var Model = require('loopback').Model;
module.exports = Model.extend('ExampleModel', properties, options);
问题是:在
boot()
期间,模型已加载,但未附加到应用程序或任何数据源。它没有公开给REST API。我尝试对
models.json
进行了少量添加,以在应用程序中启用模型:"examplemodel": {
"options": {
"base": "ExampleModel"
},
"dataSource": "db",
"public": true
}
它不起作用,回送引发
Class not found
异常。我还考虑过使用
app.model()
而不是Model.extend()
,但是我不知道如何在所需的模型app
文件中访问js
。问题:如何在
models/
目录中定义模型,并仍然将它们附加到应用程序,数据源和REST API,同时仍然依赖于所有boot()
机制? 最佳答案
如果使用slc lb project
架设了项目,则应通过app.js
主文件导出应用程序对象。
因此,您可以通过以下方式获取应用程序对象:
// in models/example-model.js
var app = require('../app.js')
拥有应用程序对象后,您可以按照正确指出的方式调用
app.model
。var properties = {
fieldOne: { type: String, required: true },
otherField: { type: Number }
};
var options = {
relations: {
collections: {
type: "belongsTo",
model: "user"
}
}
};
app.model('ExampleModel', {
properties: properties,
options: options,
dataSource: 'db' // replace with the correct name
);
// you can access the model now via
// app.models.ExampleModel