javascript - module.exports undefined 当需要 sequelize Model 类时,什么是正确的结构?
问题描述
我正在遵循 sequelize 文档来拥有一个简单的 sqlite3 db,在文档中,每件事似乎都在一个文件中,但是通过路由,我需要在不同的地方使用这些类。
我的 index.js
const express = require("express");
const applyApi = require("./src/routes").applyApi;
const { Sequelize, DataTypes, Model } = require("sequelize");
const sequelize = new Sequelize({
dialect: "sqlite",
storage: "./database.sqlite",
});
class User extends Model {}
class UserFavourite extends Model {}
User.init(
{
// Model attributes are defined here
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
// allowNull defaults to true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
passwordDigest: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
// Other model options go here
sequelize, // We need to pass the connection instance
modelName: "User", // We need to choose the model name
}
);
UserFavourite.init(
{
movieRefId: {
type: DataTypes.INTEGER,
allowNull: false,
},
movieTitle: {
type: DataTypes.STRING,
allowNull: false,
},
moviePosterPath: {
type: DataTypes.STRING,
allowNull: false,
},
seen: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
description: {
type: DataTypes.TEXT,
},
},
{
// Other model options go here
sequelize, // We need to pass the connection instance
modelName: "UserFavourite", // We need to choose the model name
}
);
User.hasMany(UserFavourite);
const app = express();
applyApi(app);
app.get("/", (req, resp) => {
resp.send("test");
});
(async () => {
try {
await sequelize.authenticate();
console.log("Connection has been established successfully.");
} catch (error) {
console.error("Unable to connect to the database:", error);
}
await sequelize.sync({ force: true });
app.listen(3001, () => {
console.log("Server started on port 3001");
});
})();
exports.models = {User, UserFavourite};
然后我导入类让我们在用户路由器中说现在它只是一个硬编码用户的测试来创建:
const userRouter = require("express").Router();
const models = require("../../../index");
userRouter.get("/", async (req, res) => {
console.log(typeof models)
console.log(models)
try{
const user = await models.models.User.create({
firstName: 'Bla',
lastName: 'BLABLA',
email: 'a@a.a',
passwordDigest: 'lklkl'
})
console.log(user)
res.send("OK")
} catch (e) {
console.log(e)
res.status(404).send("Error")
}
});
exports.userRouter = userRouter;
如您所见,我必须执行 models.models.User 等。如果尝试
const { models } =require("../../../index");
或者
const models = require("../../../index").models;
模型在控制台日志中未定义,此时我不知道为什么,console.log 上方文件中的代码段以 { models: { User: User etc... } } 的形式出现并且工作正常:models.model .User.create({userdata})
我理解的模型类不需要实例化,比如user = new User(),它只是类方法。我不介意像现在这样使用它,但我不明白这里发生了什么,谁能解释一下发生了什么?
那么我的第二个问题是,什么是一个好的文件夹结构与 sequelize 让每个类都在它自己的文件夹中并导入它,我在想像 Rails 中控制器知道模型的东西,老实说我是“翻译“我必须更好地与 NodeJS 一起使用的 Rails API。
我在 stackoverflow 上发现的唯一内容是这个链接https://github.com/sequelize/express-example但它已有 3 年历史,显然不适用于 sequelize v6,而且我不太明白模型中发生了什么文件夹。
谢谢你的时间。
解决方案
一个好的文件夹结构将是这样的。
├── models
│ ├── user.js
│ ├── userfavourites.js
│ ├── index.js
//example model
'use strict';
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define('user', {
movieRefId: {
type: DataTypes.INTEGER,
allowNull: false,
},
movieTitle: {
type: DataTypes.STRING,
allowNull: false,
},
moviePosterPath: {
type: DataTypes.STRING,
allowNull: false,
},
seen: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
description: {
type: DataTypes.TEXT
},
});
user.associate = function(models) {
// associations can be defined here
};
return user;
};
现在你想在哪里使用你的模型。
const models = require('<path>/models');
const UserModel = models.user;
推荐阅读
- reactjs - 即使 React 应用程序从与 Spring Boot 相同的端口提供服务,cookie 也未在 chrome 中设置
- c# - 从多个不同的第三方 api 或每个第三方 rest api 端点获取多个表的数据的一个表?
- html - 当它们在 HTML 中垂直堆叠/重叠时,如何使两个 Html 输入元素可见和可访问?
- html - 即使 localstorage 为空,Angular 也会在加载时显示登录用户
- html - 在 Jupyter NoteBook 中创建单选按钮(Markdown 部分)
- r - 在 R 的 {collapse} 包中,如何实现 dplyr::distinct() 或 base::unique.data.frame() 的作用?
- node.js - 使用时刻将用户定义时间转换为 UTC
- javascript - 如何从“react-navite”中的另一个屏幕调用函数?
- django - 我的视图没有在模板中呈现任何结果 - django
- excel - 汇总表的值 - 唯一值和求和值