- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
目前,我使用 Node Js 13 和 ORM Sequelize v5 以及 ES6 中的所有这些(通过 package.json 中的“type”:“module”)实现了一个 API。
在这个项目中,当我尝试使用关联时出现问题。
我有三个相关的模型:author.js、authorbook.js 和 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'
});
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'
});
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'});
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
这样的模块中。并在这里建立关联。请注意我的文件目录结构:
例如。./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 };
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
关于javascript - [NodeJs][Sequelize] ReferenceError : Cannot access 'ModelName' before initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61163520/
描述:。在我的Vue 3和nuxt 3项目中,我使用VITEST进行测试。但我在运行测试时遇到了一个问题:。版本。以下是我的页面代码:。下面是我的测试myest.spec.ts:。以下是我的vites
你好吗?我正在研究带有 Ionic 3 教程的 Google map 。我已经完成了那里解释的一切,但是当项目启动时,出现了这个错误。我调查了很多,但没有任何效果。谢谢! Error: Uncaugh
我刚刚开始使用 Node.js 并尝试使用模块。我已经安装了 Node 和 npm,并确保一切顺利。我将在下面添加代码来向您展示我得到了什么。 我有两个 js 文件,它们在这里。 app.js: va
我是 Angularjs 的初学者,在理解模块和作用域方面有些困难。 我不断收到范围未定义的错误,但我不明白为什么。首先,我将 Controller 链接到我设置路由的位置,但是由于在单击提交按钮时调
我正在制作一个 HTML 模板引擎。 程序遍历 HTML,并找到 {{ }} 的所有实例。然后它会遍历计数器中的所有键,并用对 Controller 的引用替换变量名称的实例。 例如,如果我的 Con
在我的 React Native 应用程序中,我有一个 ProductScreen,其中导入两个文件来完成屏幕。 文件 1 (Products.js) 是我的产品列表 文件 2 (Data.js) 是
我有以下类(class): class ScheduledContent { constructor(knex) { this.knex = knex } ge
在以下代码中,obj.sayhello() 行意味着sayhello在 obj 的上下文/范围内执行。 str未在 var 中定义(通过 sayhello )方法。 JS 将在范围内查找变量,即在
我正在尝试使用字符串作为函数的一部分。 const import1 = require('./import1'); const import2 = require('./import2'); //on
var g = { lang: "ttt", l: function(){ console.log(lang); } } console.log(g.l());
$(document).ready(function(){ $('#name').val('Name1'); }); function clickMe(){ console.lo
我刚刚完成了 Meteor 包的开发。现在我想通过将它添加到新的 Meteor 应用程序来测试它: my_cool_package_name/package.js Package.on_use(fun
我在给定的 SSCCE 代码中收到以下错误: Error: ReferenceError: electron is not defined Source File: http://localhost/
我正在关注一个简单的 tut,它有望构建一个响应式 slider ,但是它一直告诉我控制台中有一个错误指向一个名为 advance() 的函数 这是 slider 的简单 html:
我正在尝试使用基于按钮点击的表格中的数据填充表格。我正在将数据传递到 javascript 函数中。 )" id="modifyEdu" class="btn btn-primary"
我需要能够检查一个变量是否存在(如果它没有分配给 {})而不在 javascript 中抛出错误。当我尝试这段代码时 if (a) {} 它抛出 Uncaught ReferenceError
我在设置中有一个 mochajs 测试文件和一个 javascript 代码文件,如下所示: /js/module/codefile.js /js/test/testfile.js codefile.
我正在尝试构建一个简单的 Bookmarklet,它将一些外部 Javascript 加载到页面中,目标是将像 Stackoverflow 那样的 Markdown 编辑器添加到另一个站点。我可以使用
我有一个基于 Django 的网络应用程序。我用 Scrapy Crawler抓取网页。目前,我的目标是能够使用 jQuery 和 AJAX 请求从网页内控制爬虫。 我的理论设置如下: 在网页上,我有
以下 JavaScript... if (eval('typeof admin_post_css_theme_dark-moon)=='function')) {/**/} ...触发以下错误消息..
我是一名优秀的程序员,十分优秀!