gpt4 book ai didi

loopbackjs - Loopback 中的动态模型

转载 作者:行者123 更新时间:2023-12-02 03:36:55 25 4
gpt4 key购买 nike

如何在环回中创建动态模型,而不是对所有模型使用命令“lb model”。

例如: 如果我想创建 30 个具有几乎相同属性的模型,那么会遇到一次又一次创建所有 30 个模型和那些相应属性的麻烦。

是否可以创建模型并使用环回将其迭代到另一个模型。请分享您的答案。

最佳答案

嗯,我对此还很陌生,但我认为,您可以轻松地以编程方式创建任意数量的动态模型。例如,首先,在 boot 目录中创建一个启动脚本,例如:server\boot\dynamic-models.js,然后使用以下代码创建动态模型:

const app = require('../server');
const dbDataSource = app.datasources.db;
const schema = {
"name": {
"type": "string",
"required": true
},
"email": {
"type": "string",
"required": true
}
};

const MyDynamicModel = dbDataSource.createModel('MyDynamicModel', schema);

app.model(MyDynamicModel);

app 是从 projectroot/server/server.js 导出的,因此您可以在脚本中使用它。

此外,模式是可选的(在 noSql/mongo 的情况下)。创建动态模型后,您可以访问 api 资源管理器并可以查看动态创建的模型/端点。

如果您要创建更多模型,那么您只需执行循环并创建模型即可,例如:

const models = ['ModelOne', 'ModelTwo'];
// or export from other files and import those here, i.e:
// const schema = require('exported-from-another-file');
// const models = require('exported-from-another-file');
models.forEach(model => {
app.model(dbDataSource.createModel(model, schema));
});

更新:多个模型动态注册的另一个工作示例:

// project-root/common/dynamic/index.js
module.exports.schema = {
"name": {
"type": "string",
"required": true
},
"email": {
"type": "string",
"required": true
}
};

module.exports.models = [
'ModelOne',
'ModelTwo'
];
// project-root/server/boot/dynamic-models.js
const app = require('../server');
const dbDataSource = app.datasources.db;
const {schema, models} = require('../../common/dynamic');
models.forEach(
model => app.model(dbDataSource.createModel(model, schema))
);

现在,要使用相同架构添加任何动态模型,您只需在模型数组中添加模型名称即可。这已经过测试并且工作正常:

enter image description here

关于loopbackjs - Loopback 中的动态模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49914970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com