无法设置我的loopback模型。错误:持久模型未正确附加到DataSource

问题描述 投票:0回答:2
restraunt.json file

`{
  "name": "restraunt",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "location": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}`

restraunt.js file

`module.exports = function(Restraunt) {
    Restraunt.find({where:{id:1}}, function(data) {
        console.log(data);
    })
};`

model-config.json  file
`"restraunt": {
    "dataSource": "restrauntManagement"
  }`

datasources.json file
`{
  "db": {
    "name": "db",
    "connector": "memory"
  },
  "restrauntManagement": {
    "host": "localhost",
    "port": 0,
    "url": "",
    "database": "restraunt-management",
    "password": "restraunt-management",
    "name": "restrauntManagement",
    "user": "rohit",
    "connector": "mysql"
  }
}`

我能够从资源管理器获取,放置,发布,这意味着sql db已正确设置,但我无法从restraunt.js文件中“找到”。它会抛出错误。 “错误:无法调用restraunt.find()。尚未设置find方法.PersistedModel尚未正确附加到DataSource”

loopback
2个回答
0
投票

尝试再次安装mysql连接器:

npm i -S loopback-connector-mysql

看看你的datasources.json,因为mysql的端口可能是错误的,默认端口是3306,你也可以尝试将localhost更改为0.0.0.0。

"restrauntManagement": {
    "host": "localhost", /* if you're using docker, you need to set it to 0.0.0.0 instead of localhost */
    "port": 0, /* default port is 3306 */
    "url": "",
    "database": "restraunt-management",
    "password": "restraunt-management",
    "name": "restrauntManagement", 
    "user": "rohit",
    "connector": "mysql"
  }

model-config.json必须是:

"restraunt": {
    "dataSource": "restrauntManagement" /* this name must be the same name in datasources object key (in your case it is restrauntManagement not the connector name which is mysql) */
  }

您还需要执行餐馆模型的迁移:

在/ server / boot创建migration.js并添加:

'use strict';

module.exports = function(server) {
  var mysql = server.dataSources.mysql; 

  mysql.autoupdate('restraunt');
};

您需要迁移您将使用它的每个模型。如果要将它们附加到数据源,还需要迁移默认模型(ACL,AccessToken等)。

同样在文档中说你不能在model.js文件中执行任何操作,因为系统(在那一点上)它没有完全加载。您需要执行的任何操作必须位于/ boot目录中的.js文件中,因为系统已在那里完全加载。您可以在远程方法中执行操作,因为系统也已加载。


0
投票

除了在boot文件夹中执行代码之外,还可以使用在附加模型后发出的事件。您可以在model.js中编写代码,而不是在boot文件夹中编写代码。

好像:

Model.once("attached", function () {})

Model = Accounts (for example).

我知道,这是一个古老的话题,但也许这有助于其他人。

© www.soinside.com 2019 - 2024. All rights reserved.