<i id='PVjiE'><tr id='PVjiE'><dt id='PVjiE'><q id='PVjiE'><span id='PVjiE'><b id='PVjiE'><form id='PVjiE'><ins id='PVjiE'></ins><ul id='PVjiE'></ul><sub id='PVjiE'></sub></form><legend id='PVjiE'></legend><bdo id='PVjiE'><pre id='PVjiE'><center id='PVjiE'></center></pre></bdo></b><th id='PVjiE'></th></span></q></dt></tr></i><div id='PVjiE'><tfoot id='PVjiE'></tfoot><dl id='PVjiE'><fieldset id='PVjiE'></fieldset></dl></div>

        • <bdo id='PVjiE'></bdo><ul id='PVjiE'></ul>
        <legend id='PVjiE'><style id='PVjiE'><dir id='PVjiE'><q id='PVjiE'></q></dir></style></legend>

        <small id='PVjiE'></small><noframes id='PVjiE'>

      1. <tfoot id='PVjiE'></tfoot>

        [NodeJs][Sequelize] ReferenceError:初始化前无法访问“ModelName"

        [NodeJs][Sequelize] ReferenceError: Cannot access #39;ModelName#39; before initialization([NodeJs][Sequelize] ReferenceError:初始化前无法访问“ModelName)
        1. <tfoot id='6SaEG'></tfoot>
          <i id='6SaEG'><tr id='6SaEG'><dt id='6SaEG'><q id='6SaEG'><span id='6SaEG'><b id='6SaEG'><form id='6SaEG'><ins id='6SaEG'></ins><ul id='6SaEG'></ul><sub id='6SaEG'></sub></form><legend id='6SaEG'></legend><bdo id='6SaEG'><pre id='6SaEG'><center id='6SaEG'></center></pre></bdo></b><th id='6SaEG'></th></span></q></dt></tr></i><div id='6SaEG'><tfoot id='6SaEG'></tfoot><dl id='6SaEG'><fieldset id='6SaEG'></fieldset></dl></div>

          • <small id='6SaEG'></small><noframes id='6SaEG'>

              <tbody id='6SaEG'></tbody>
              • <bdo id='6SaEG'></bdo><ul id='6SaEG'></ul>
                  <legend id='6SaEG'><style id='6SaEG'><dir id='6SaEG'><q id='6SaEG'></q></dir></style></legend>
                  本文介绍了[NodeJs][Sequelize] ReferenceError:初始化前无法访问“ModelName"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  目前我使用 Node Js 13 和 ORM Sequelize v5 实现了一个 API,所有这些都在 ES6 中(通过type":模块"在 package.json).

                  Currently I realize an API using Node Js 13 and the ORM Sequelize v5 and all this in ES6 (via "type": "module" in package.json).

                  在这个项目中,当我尝试使用关联时出现问题.

                  In this project there is a problem when I try to use associations.

                  我有三个关联的模型:author.js、authorbook.js 和 book.js.

                  I have three models which are associated: author.js, authorbook.js and book.js .

                  作者.js:

                  import Sequelize from 'sequelize';
                  import AuthorBook from './authorbook.js';
                  import dotenv from 'dotenv';
                  
                  dotenv.config();
                  
                  const sequelize = new Sequelize(
                    process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{
                      host: process.env.DB_HOST,
                      dialect: 'mysql'
                    }
                  );
                  
                  export default class Author extends Sequelize.Model {}
                  Author.init({
                    firstName: {
                      firstName: false,
                      type: Sequelize.STRING(100)
                    },
                    lastName: {
                      allowNull: false,
                      type: Sequelize.STRING(100)
                    }
                  }, { sequelize });
                  
                  Author.hasMany(AuthorBook, {
                    onUpdate: 'CASCADE'
                  });
                  

                  book.js:

                  import Sequelize from 'sequelize';
                  import AuthorBook from './authorbook.js';
                  import dotenv from 'dotenv';
                  
                  dotenv.config();
                  
                  const sequelize = new Sequelize(
                    process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{
                      host: process.env.DB_HOST,
                      dialect: 'mysql'
                    }
                  );
                  
                  export default class Book extends Sequelize.Model {}
                  Book.init({
                    title: {
                      firstName: false,
                      type: Sequelize.STRING(100)
                    }
                  }, { sequelize });
                  
                  Book.hasMany(AuthorBook, {
                    onUpdate: 'CASCADE'
                  });
                  

                  authorbook.js:

                  import Sequelize from 'sequelize';
                  import Author from './author.js';
                  import Book from './book.js';
                  import dotenv from 'dotenv';
                  
                  dotenv.config();
                  
                  const sequelize = new Sequelize(
                    process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD,{
                      host: process.env.DB_HOST,
                      dialect: 'mysql'
                    }
                  );
                  
                  export default class AuthorBook extends Sequelize.Model {}
                  AuthorBook.init({
                    authorId: {
                      type: Number,
                      allowNull: false
                    },
                    bookId: {
                      type: Number,
                      allowNull: false
                    },
                  }, { sequelize });
                  
                  AuthorBook.belongsTo(Author, { foreignKey: 'authorId'});
                  AuthorBook.belongsTo(Book, { foreignKey: 'bookId'});
                  

                  这是我在运行 cmd node src/server.js 时遇到的错误:

                  Here is the error I get when I run the cmd node src/server.js:

                  (node:23142) ExperimentalWarning: The ESM module loader is experimental.
                  file:///Users/alexandre/Documents/project/server/src/db/models/.js:18
                  Author.hasMany(AuthorBook, {
                                 ^
                  
                  ReferenceError: Cannot access 'AuthorBook' before initialization
                      at file:///Users/alexandre/Documents/project/server/src/db/models/author.js:38:22
                      at ModuleJob.run (internal/modules/esm/module_job.js:110:37)
                      at async Loader.import (internal/modules/esm/loader.js:176:24)
                  

                  有人可以帮助我吗?

                  推荐答案

                  这个错误意味着你的模块之间存在循环引用.您应该将模型放在 index.ts 之类的模块中,并在此处进行关联.请注意我的文件目录结构:

                  The error means there are circular references between your modules. You should put the models in a module like index.ts and make the associations here. Please pay attention to my file directory structure:

                  例如

                  ./models/book.ts:

                  import Sequelize from 'sequelize';
                  import { sequelize } from '../../../db';
                  
                  export default class Book extends Sequelize.Model {}
                  Book.init(
                    {
                      title: {
                        allowNull: false,
                        type: Sequelize.STRING(100),
                      },
                    },
                    { sequelize, modelName: 'books' },
                  );
                  

                  ./models/author.ts:

                  import Sequelize from 'sequelize';
                  import { sequelize } from '../../../db';
                  
                  export default class Author extends Sequelize.Model {}
                  Author.init(
                    {
                      firstName: {
                        allowNull: false,
                        type: Sequelize.STRING(100),
                      },
                      lastName: {
                        allowNull: false,
                        type: Sequelize.STRING(100),
                      },
                    },
                    { sequelize, modelName: 'authors' },
                  );
                  

                  ./models/authorbook.ts:

                  import Sequelize from 'sequelize';
                  import { sequelize } from '../../../db';
                  
                  export default class AuthorBook extends Sequelize.Model {}
                  AuthorBook.init(
                    {
                      authorId: {
                        type: Sequelize.INTEGER,
                        allowNull: false,
                      },
                      bookId: {
                        type: Sequelize.INTEGER,
                        allowNull: false,
                      },
                    },
                    { sequelize, modelName: 'authorbooks' },
                  );
                  

                  ./models/index.ts:

                  import Author from './author';
                  import Book from './book';
                  import AuthorBook from './authorbook';
                  
                  Author.hasMany(AuthorBook, {
                    onUpdate: 'CASCADE',
                  });
                  Book.hasMany(AuthorBook, {
                    onUpdate: 'CASCADE',
                  });
                  AuthorBook.belongsTo(Author, { foreignKey: 'authorId' });
                  AuthorBook.belongsTo(Book, { foreignKey: 'bookId' });
                  
                  export { Author, Book, AuthorBook };
                  

                  现在,我们可以使用这些模型了.

                  Now, we can use these models.

                  index.ts:

                  import { Author, AuthorBook, Book } from './models';
                  import { sequelize } from '../../db';
                  import faker from 'faker';
                  
                  (async function test() {
                    try {
                      await sequelize.sync({ force: true });
                      // seed
                      const author = await Author.create({
                        firstName: faker.name.firstName(),
                        lastName: faker.name.lastName(),
                      });
                      const book = await Book.create({
                        title: faker.lorem.words(3),
                      });
                      await AuthorBook.create({ authorId: author.id, bookId: book.id });
                    } catch (error) {
                      console.log(error);
                    } finally {
                      await sequelize.close();
                    }
                  })();
                  

                  执行结果:

                  Executing (default): DROP TABLE IF EXISTS "authorbooks" CASCADE;
                  Executing (default): DROP TABLE IF EXISTS "books" CASCADE;
                  Executing (default): DROP TABLE IF EXISTS "authors" CASCADE;
                  Executing (default): DROP TABLE IF EXISTS "authors" CASCADE;
                  Executing (default): CREATE TABLE IF NOT EXISTS "authors" ("id"   SERIAL , "firstName" VARCHAR(100) NOT NULL, "lastName" VARCHAR(100) NOT NULL, PRIMARY KEY ("id"));
                  Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'authors' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
                  Executing (default): DROP TABLE IF EXISTS "books" CASCADE;
                  Executing (default): CREATE TABLE IF NOT EXISTS "books" ("id"   SERIAL , "title" VARCHAR(100) NOT NULL, PRIMARY KEY ("id"));
                  Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'books' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
                  Executing (default): DROP TABLE IF EXISTS "authorbooks" CASCADE;
                  Executing (default): CREATE TABLE IF NOT EXISTS "authorbooks" ("id"   SERIAL , "authorId" INTEGER NOT NULL REFERENCES "authors" ("id") ON DELETE CASCADE ON UPDATE CASCADE, "bookId" INTEGER NOT NULL REFERENCES "books" ("id") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY ("id"));
                  Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'authorbooks' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
                  Executing (default): INSERT INTO "authors" ("id","firstName","lastName") VALUES (DEFAULT,$1,$2) RETURNING *;
                  Executing (default): INSERT INTO "books" ("id","title") VALUES (DEFAULT,$1) RETURNING *;
                  Executing (default): INSERT INTO "authorbooks" ("id","authorId","bookId") VALUES (DEFAULT,$1,$2) RETURNING *;
                  

                  检查数据库:

                  node-sequelize-examples=# select * from "authors";
                   id | firstName | lastName
                  ----+-----------+----------
                    1 | Laron     | Deckow
                  (1 row)
                  
                  node-sequelize-examples=# select * from "books";
                   id |          title
                  ----+-------------------------
                    1 | facilis molestias sequi
                  (1 row)
                  
                  node-sequelize-examples=# select * from "authorbooks";
                   id | authorId | bookId
                  ----+----------+--------
                    1 |        1 |      1
                  (1 row)
                  

                  依赖版本:"sequelize": "^5.21.3", postgres:9.6

                  源代码:https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/61163520

                  这篇关于[NodeJs][Sequelize] ReferenceError:初始化前无法访问“ModelName"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Pause youtube video, youtube api(暂停 youtube 视频,youtube api)
                  Youtube iframe api not triggering onYouTubeIframeAPIReady(Youtube iframe api 未触发 onYouTubeIframeAPIReady)
                  How can I stop a video with Javascript in Youtube?(如何在 Youtube 中停止使用 Javascript 的视频?)
                  How to call Greasemonkey#39;s GM_ functions from code that must run in the target page scope?(如何从必须在目标页面范围内运行的代码中调用 Greasemonkey 的 GM_ 函数?)
                  How do you mute an embedded Youtube player?(如何使嵌入式 Youtube 播放器静音?)
                  How to get number of video views with YouTube API?(如何使用 YouTube API 获取视频观看次数?)
                • <small id='RHhJk'></small><noframes id='RHhJk'>

                      <bdo id='RHhJk'></bdo><ul id='RHhJk'></ul>
                      <tfoot id='RHhJk'></tfoot>

                      <i id='RHhJk'><tr id='RHhJk'><dt id='RHhJk'><q id='RHhJk'><span id='RHhJk'><b id='RHhJk'><form id='RHhJk'><ins id='RHhJk'></ins><ul id='RHhJk'></ul><sub id='RHhJk'></sub></form><legend id='RHhJk'></legend><bdo id='RHhJk'><pre id='RHhJk'><center id='RHhJk'></center></pre></bdo></b><th id='RHhJk'></th></span></q></dt></tr></i><div id='RHhJk'><tfoot id='RHhJk'></tfoot><dl id='RHhJk'><fieldset id='RHhJk'></fieldset></dl></div>
                        <tbody id='RHhJk'></tbody>

                      <legend id='RHhJk'><style id='RHhJk'><dir id='RHhJk'><q id='RHhJk'></q></dir></style></legend>