Node.js Sequelize :ReferenceError:模型未定义,使用通过关联时

问题描述 投票:0回答:1

我需要在续集中创建多对多关联。

我遇到了这个错误:

ReferenceError: alertSMSRule is not defined

这是有关错误的代码:

文件alertSMSrule.model.js:

module.exports = (sequelize, Sequelize) => {
    const AlertSMSRule = sequelize.define("alertSMSRule", {
      name: {
        type: Sequelize.STRING
      },
      number: {
        type: Sequelize.STRING
      }
    });
  
    return AlertSMSRule;
  };

文件phoneNumber.model.js:

module.exports = (sequelize, Sequelize) => {
    const PhoneNumber = sequelize.define("phoneNumber", {
      name: {
        type: Sequelize.STRING
      },
      number: {
        type: Sequelize.STRING
      }
    });
  
    return PhoneNumber;
  };

文件index.js:

db.phoneNumber = require("./phoneNumber.model.js")(sequelize, Sequelize);
db.alertSMSRule = require("./alertSMSRule.model.js")(sequelize, Sequelize);

// line below is giving the error
alertSMSRule.belongsToMany(phoneNumber, { through: 'SMSRule_PhoneNumbers' });
phoneNumber.belongsToMany(alertSMSRule, { through: 'SMSRule_PhoneNumbers' });

Sequelize 已正确导入并初始化。 我有很多其他模型关联工作得很好,但它们都是 hasMany / BelongsTo。 这是我的第一个 ownToMany 关联,也是唯一一个有错误的关联。

我是否错过了与sequelize 创建多对多关联的一些事情? 我检查了续集文档和论坛,一切都告诉我这应该以这种方式工作。 资料来源:https://sequelize.org/docs/v6/advanced-association-concepts/advanced-many-to-many/

javascript node.js model sequelize.js
1个回答
0
投票

我发现问题所在了。正如我们在一些论坛上看到的,这是一个 Javascript 错误,与 Node.js 或 Sequelize 无关。

我更换了代码:

alertSMSRule.belongsToMany(phoneNumber, { through: 'SMSRule_PhoneNumbers' });
phoneNumber.belongsToMany(alertSMSRule, { through: 'SMSRule_PhoneNumbers' });

作者:

db.alertSMSRule.belongsToMany(phoneNumber, { through: 'SMSRule_PhoneNumbers' });
db.phoneNumber.belongsToMany(alertSMSRule, { through: 'SMSRule_PhoneNumbers' });
© www.soinside.com 2019 - 2024. All rights reserved.