首页 > 数据库 >node.js: mysql sequelize es6 ORM in vscode

node.js: mysql sequelize es6 ORM in vscode

时间:2024-08-09 08:54:13浏览次数:12  
标签:node es6 const vscode res js tutorials id Tutorial

mysql:

select * from tutorials;
# CREATE TABLE IF NOT EXISTS `tutorials` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255), `description` VARCHAR(255), `published` TINYINT(1), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
insert into tutorials values(1,'geovindu','geovidu',1,'2025-05-04','2025-05-04');
insert into tutorials values(2,'涂聚文','涂聚文',0,'2025-05-04','2025-05-04');

  

/**
 * dbConfig.js
 * node 20 vue.js 3.0
 * ide: vscode
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 */
 
 
const dbConfig = {
    HOST: "localhost",
    USER: "root",
    PASSWORD: "geovindu",
    DB: "geovindu",
    dialect: "mysql",
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    }
  };
 
  export default dbConfig;
 
  /**
   * select * from tutorials;
# CREATE TABLE IF NOT EXISTS `tutorials` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255), `description` VARCHAR(255), `published` TINYINT(1), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
insert into tutorials values(1,'geovindu','geovidu',1,'2025-05-04','2025-05-04');
insert into tutorials values(2,'涂聚文','涂聚文',2,'2025-05-04','2025-05-04');
   *
   */
 
 
/**
 * models/tutorial.model.js
 * node 20 vue.js 3.0
 * ide: vscode
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 */
 
//module.exports
const Tutorial = (sequelize, Sequelize) => {
    const Tutorial = sequelize.define("tutorial", {
      title: {
        type: Sequelize.STRING
      },
      description: {
        type: Sequelize.STRING
      },
      published: {
        type: Sequelize.BOOLEAN
      }
    });
   
    return Tutorial;
  };
 
  export default Tutorial;
 
 
/**
 * models/index.js
 * node 20 vue.js 3.0
 * ide: vscode
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 */
 
import dbConfig from "../db.config.js";
import Sequelize from "sequelize";
import tutorials from "./tutorial.model.js"
 
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorsAliases: false,
 
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
});
 
const db = {};
 
db.Sequelize = Sequelize;
db.sequelize = sequelize;
 
//db.tutorials = require("./tutorial.model.js")(sequelize, Sequelize);
 db.tutorials=tutorials(sequelize, Sequelize);
 
//module.exports = db;
export default db;
 
 
/**
 * controllers/tutorial.controller.js
 * node 20 vue.js 3.0
 * ide: vscode
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 */
 
import db  from "../models/index.js";
 
const Tutorial = db.tutorials;
const Op = db.Sequelize.Op;
 
//module.exports.
 const create = (req, res) => {
    // Validate request
    if (!req.body.title) {
      res.status(400).send({
        message: "Content can not be empty!"
      });
      return;
    }
   
    // Create a Tutorial
    const tutorial = {
      title: req.body.title,
      description: req.body.description,
      published: req.body.published ? req.body.published : false
    };
   
    // Save Tutorial in the database
    Tutorial.create(tutorial)
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while creating the Tutorial."
        });
      });
  };
 
  //exports.create;
 // exports.create = create;
 
//module.exports.
 
const  findAll = (req, res) => {
    const title = req.query.title;
    var condition = title ? { title: { [Op.like]: `%${title}%` } } : null;
   
    Tutorial.findAll({ where: condition })
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving tutorials."
        });
      });
  };
 
  //exports.findAll = findAll;
//findByPk
//module.exports.
 
const findOne = (req, res) => {
    const id = req.params.id;
   
    Tutorial.findByPk(id)
      .then(data => {
        if (data) {
          res.send(data);
        } else {
          res.status(404).send({
            message: `Cannot find Tutorial with id=${id}.`
          });
        }
      })
      .catch(err => {
        res.status(500).send({
          message: "Error retrieving Tutorial with id=" + id
        });
      });
  };
 
 
  //exports.findOne = findOne;
//  module.exports.
const update = (req, res) => {
    const id = req.params.id;
   
    Tutorial.update(req.body, {
      where: { id: id }
    })
      .then(num => {
        if (num == 1) {
          res.send({
            message: "Tutorial was updated successfully."
          });
        } else {
          res.send({
            message: `Cannot update Tutorial with id=${id}. Maybe Tutorial was not found or req.body is empty!`
          });
        }
      })
      .catch(err => {
        res.status(500).send({
          message: "Error updating Tutorial with id=" + id
        });
      });
  };
 
 // exports.update = update;
 
//destroy module.exports.
const deleteid = (req, res) => {
    const id = req.params.id;
   
    Tutorial.destroy({
      where: { id: id }
    })
      .then(num => {
        if (num == 1) {
          res.send({
            message: "Tutorial was deleted successfully!"
          });
        } else {
          res.send({
            message: `Cannot delete Tutorial with id=${id}. Maybe Tutorial was not found!`
          });
        }
      })
      .catch(err => {
        res.status(500).send({
          message: "Could not delete Tutorial with id=" + id
        });
      });
  };
 
  //exports.Delete = Delete; 
 
//destroy module.exports
const deleteAll = (req, res) => {
    Tutorial.destroy({
      where: {},
      truncate: false
    })
      .then(nums => {
        res.send({ message: `${nums} Tutorials were deleted successfully!` });
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while removing all tutorials."
        });
      });
  };
 
 
   
  //exports.deleteAll = deleteAll;
//module.exports.
const findAllPublished = (req, res) => {
    Tutorial.findAll({ where: { published: true } })
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving tutorials."
        });
      });
  };
 
  //exports.findAllPublished = findAllPublished;
 
  // 这个命名问题 tutorials
// 使用 ES6 的默认导出语法,直接导出包含所有函数的对象
 export default
  {
    findAllPublished,
    deleteAll,
    deleteid,
    update,
    findOne,
    findAll,
    create
  };
 
 //function
//module.exports={findAllPublished,deleteAll,Delete,update,findOne,findAll,create};
 
 
/**
 * routes/tutorial.routes.js
 * node 20 vue.js 3.0
 * ide: vscode
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 * https://www.bezkoder.com/node-js-express-sequelize-mysql/
 * 路由报错,还没有配置好 数据库连接OK
 */
 
import express from "express"
import tutorials from "../controllers/tutorial.controller.js"
//import Tutorial from "../models/tutorial.model.js";
 
//module.exports
 const routes= app => {
    //const tutorials = require("../controllers/tutorial.controller.js");
     
    var router = express.Router();
   
     
 
    // Create a new Tutorial
    //app.post("/", Tutorial.findAll);
    router.post("/",tutorials.create)
 
    // Retrieve all Tutorials
    router.get("/", tutorials.findAll);
  /**/
    // Retrieve all published Tutorials
    router.get("/published", tutorials.findAll);
   
    // Retrieve a single Tutorial with id
    router.get("/:id", tutorials.findOne);
   
    // Update a Tutorial with id
    router.put("/:id", tutorials.update);
   
    // Delete a Tutorial with id
    router.put("/:id", tutorials.deleteid);
   
    // Delete all Tutorials
    router.put("/", tutorials.deleteAll);
   
    //app.use('/api/tutorials', router);
    app.use('/api/tutorials',router);
  };
 
  export default routes;
 
/**
 * server.js
 * node 20 vue.js 3.0
 * ide: vscode
 * mysql 8.0
 * npm install express sequelize mysql2 cors
 */
 
 
import express from "express";
import cors from "cors";
import db from "./models/index.js"
import routes from "./routes/turorial.routes.js"
 
 
const Tutorial = db.tutorials;
 
//require("./app/routes/turorial.routes")(app);
 
const app = express();
 
//var routes =require("./app/routes/turorial.routes");
 
routes(app);
//app.routes();
 
var corsOptions = {
  origin: "http://localhost:8080"
};
 
app.use(cors(corsOptions));
 
// parse requests of content-type - application/json
app.use(express.json());
 
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
 
 
//http://localhost:8080/models
///http://localhost:8080/tutorials
//const db = require("./app/models");
db.sequelize.sync()
  .then(() => {
    console.log("Synced db.");
  })
  .catch((err) => {
    console.log("Failed to sync db: " + err.message);
  });
 
  //routes(app); //这行路由编译报错
 
// simple route
app.get("/", (req, res) => {
 
/*
  if (!req.body.title) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
    return;
  }
*/
  // Create a Tutorial
  const tutorial = {
    title: '兴大兴',
    description: '涂没有什么',
    published: false,
    createdAt:'2024-08-05',
    updatedAt:'2024-08-05'
  };
 
  // Save Tutorial in the database
  Tutorial.create(tutorial)
    .then(data => {
      res.send(data);     
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Tutorial."
      });
    });
 
    res.json({ message: "数据添加成功!." });
 
});
 
// set port, listen for requests  http://localhost:8080
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
 
 
 
 

  

进入当前文件夹下运行:

node server

  

 

标签:node,es6,const,vscode,res,js,tutorials,id,Tutorial
From: https://www.cnblogs.com/geovindu/p/18350112

相关文章

  • 轮换挑选图片,补充 es6的对象写法,uniapp使用,class和style,条件渲染,列表渲染,input
    Ⅰ轮换挑选图片【一】方式一<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><scriptsrc="./js2/vue.js"></script></head><body>......
  • ES6对数据类型都做了那些优化
    ES6 对String字符串类型做优化:ES6 新增了字符串模板,在拼接大段字符串时,用反斜杠(、)取代以往的字符串相加的形式,能保留所有空格和换行,使得字符串拼接看起来更加直观,更加优雅。ES6对Array数组类型做优化:1、数组解构赋值ES6可以直接以let[a,b,c]=[1,2,3]形式进......
  • 书生.浦江大模型实战训练营——(一)InternStudio+Vscode SSH连接远程服务器+Linux基础指
    最近在学习书生.浦江大模型实战训练营,所有课程都免费,以关卡的形式学习,也比较有意思,提供免费的算力实战,真的很不错(无广)!欢迎大家一起学习,打开LLM探索大门:邀请连接,PS,邀请有算力哈哈。文章目录一、InternStudio使用二、VscodeSSH连接远程服务器三、Linux基础指令一......
  • 利用vscode-icons-js在Vue3项目中实现文件图标展示
    背景:在开发文件管理系统或类似的项目时,我们常常需要根据文件类型展示对应的文件图标,这样可以提高用户体验。本文将介绍如何在Vue3项目中利用vscode-icons-js库,实现类似VSCode的文件图标展示效果。先看效果:一、引入vscode-icons-js首先,我们需要安装vscode-icons-js库。......
  • git前端上传项目忽略本地node_modules文件
    要在Git上传前端代码时忽略node_modules文件夹在项目根目录下查找或创建.gitignore文件:如果你的项目中已经存在.gitignore文件,则打开它进行编辑。如果不存在,就在项目根目录下创建一个新的.gitignore文件。在.gitignore文件中添加node_modules/:打开.gitignore文件,并添加......
  • VsCode C++ namespace has no member错误
    此问题VSCode C++插件本身bug解决办法一:还原c++插件到旧版本解决方法二:但此方法智能提示会有很多多余的信息(有缺陷)在官方未推出相应布丁之前,可按照以下步骤避免该问题:1、按顺序打开:文件》首选项》设置2、在右边,用户设置窗口添加以下代码:"C_Cpp.intelliSenseEngine":"TagP......
  • windows平台中使用vscode远程连接linux进行c++开发配置教程(内容详细适合小白)-2021-3-3
    文章目录一、简要介绍二、软件安装步骤1.linux系统安装2.vscode安装3.ssh安装4.配置Remote-SSH5.安装远程插件6.简单小测试三、配置vscode开发环境1.默认设置、用户设置、远程设置和工作区设置2.c++开发设置a).c_cpp_properties.jsonb).tasks.jsonc).launc......
  • 计算机毕业设计项目推荐,院系资料分类管理平台 84184(开题答辩+程序定制+全套文案 )上万
    目 录摘要1绪论1.1研究背景1.2研究意义1.3论文结构与章节安排2 院系资料分类管理平台系统分析2.1可行性分析2.2系统流程分析2.2.1数据增加流程2.2.2数据修改流程2.2.3数据删除流程2.3系统功能分析2.3.1功能性分析2.3.2非功能性分析......
  • 计算机毕业设计项目推荐,红色旅游网站设计与开发 99214(开题答辩+程序定制+全套文案 )上
    摘 要21世纪时信息化的时代,几乎任何一个行业都离不开计算机,将计算机运用于旅游服务管理也是十分常见的。过去使用手工的管理方式对旅游服务进行管理,造成了管理繁琐、难以维护等问题,如今使用计算机对旅游服务的各项基本信息进行管理,比起手工管理来说既方便又简单,而且具有易......
  • Electron + Vue+Node.js 搭建前端桌面应用
    一、在使用Electron之前我们要了解Electron是什么?Electron官网地址点此: electron官方地址Electron相当于一个浏览器的外壳,我们将编写的HTML,CSS,Javascript网页程序嵌入进Electron里面以便于在桌面上进行运行。通俗来讲它就是一个软件,如QQ、网易......