node.js: mysql sequelize es6 ORM in vscode
mysql:
1 2 3 4 | 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' ); |
1 2 3 | # http://localhost:8080/api/tutorials/ user /* CREATE TABLE IF NOT EXISTS `userInfos` (`id` INTEGER NOT NULL auto_increment , `userName` VARCHAR(255), `userPassword` VARCHAR(255), `userIsOk` TINYINT(1), `userMail` VARCHAR(255), `userMobile` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB; */ insert into userinfos values (1, 'geovindu' , 'geovindu' ,1, 'geovindu@163.com' , '13824350518' , '2025-07-09' , '2025-09-01' ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 | /** * 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}.`); }); |
进入当前文件夹下运行:
1 | node server |
运行创建数据表
一台有报错误也执行了。一台无报错,也执行了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | /** * models/userinfo.model.js * node 20 vue.js 3.0 * ide: vscode * mysql 9.0 * npm install express sequelize mysql2 cors */ /** * userInfo 实体 * @param {*} sequelize * @param {*} Sequelize * @returns */ const UserInfo = (sequelize, Sequelize) => { const UserInfo = sequelize.define( "userInfo" , { userName: { type: Sequelize.STRING }, userPassword: { type: Sequelize.STRING }, userIsOk: { type: Sequelize.BOOLEAN }, userMail: { type:Sequelize.STRING }, userMobile: { type:Sequelize.STRING } }); return UserInfo; }; export default UserInfo; /** * controllers/userinfo.controller.js * node 20 vue.js 3.0 * ide: vscode * mysql 9.0 * npm install express sequelize mysql2 cors */ import db from "../models/index.js" ; const UserInfo = db.userinfos; const Op = db.Sequelize.Op; /** * * @param {*} req * @param {*} res * @returns */ const usercreate = (req, res) => { // Validate request if (!req.body.title) { res.status(400).send({ message: "Content can not be empty!" }); return ; } // Create a Tutorial const userInfo = { userName: req.body.userName, userPassword: req.body.userPassword, userIsOk: req.body.userIsOk ? req.body.userIsOk : false , userMail:req.body.userMail, userMobile:req.body.userMobile }; // Save Tutorial in the database UserInfo.create(userInfo) .then(data => { res.send(data); }) . catch (err => { res.status(500).send({ message: err.message || "Some error occurred while creating the userinfos." }); }); }; /** * * @param {*} req * @param {*} res */ const userfindAll = (req, res) => { const userName = req.query.userName; var condition = userName ? { userName: { [Op.like]: `%${userName}%` } } : null ; UserInfo.findAll({ where: condition }) .then(data => { res.send(data); }) . catch (err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving userinfos." }); }); }; /** * * @param {*} req * @param {*} res */ const userfindOne = (req, res) => { const id = req.params.id; UserInfo.findByPk(id) .then(data => { if (data) { res.send(data); } else { res.status(404).send({ message: `Cannot find userinfos with id=${id}.` }); } }) . catch (err => { res.status(500).send({ message: "Error retrieving userinfos with id=" + id }); }); }; /** * * @param {*} req * @param {*} res */ const userupdate = (req, res) => { const id = req.params.id; UserInfo.update(req.body, { where: { id: id } }) .then(num => { if (num == 1) { res.send({ message: "usrinfos was updated successfully." }); } else { res.send({ message: `Cannot update userinfos with id=${id}. Maybe userinfos was not found or req.body is empty!` }); } }) . catch (err => { res.status(500).send({ message: "Error updating userinfos with id=" + id }); }); }; /** * * @param {*} req * @param {*} res */ const userdeleteid = (req, res) => { const id = req.params.id; UserInfo.destroy({ where: { id: id } }) .then(num => { if (num == 1) { res.send({ message: "userinfos was deleted successfully!" }); } else { res.send({ message: `Cannot delete userinfos with id=${id}. Maybe userinfos was not found!` }); } }) . catch (err => { res.status(500).send({ message: "Could not delete userinfos with id=" + id }); }); }; /** * * @param {*} req * @param {*} res */ const userdeleteAll = (req, res) => { UserInfo.destroy({ where: {}, truncate: false }) .then(nums => { res.send({ message: `${nums} userinfos were deleted successfully!` }); }) . catch (err => { res.status(500).send({ message: err.message || "Some error occurred while removing all userinfos." }); }); }; /** * * @param {*} req * @param {*} res */ const findAlluserIsOk = (req, res) => { UserInfo.findAll({ where: { userIsOk: true } }) .then(data => { res.send(data); }) . catch (err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving userinfos." }); }); }; // 这个命名问题 tutorials // 使用 ES6 的默认导出语法,直接导出包含所有函数的对象 export default { findAlluserIsOk, userdeleteAll, userdeleteid, userupdate, userfindOne, userfindAll, usercreate }; /** * routes/tutorial.routes.js * node 20 vue.js 3.0 * ide: vscode * mysql 9.0 * npm install express sequelize mysql2 cors * https://www.bezkoder.com/node-js-express-sequelize-mysql/ * 路由ok,有配置好 数据库连接OK */ import express from "express" import tutorials from "../controllers/tutorial.controller.js" import userinfos from "../controllers/userinfo.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) router.post( "/user" ,userinfos.usercreate) // Retrieve all Tutorials router.get( "/" , tutorials.findAll); router.get( "/user" , userinfos.userfindAll); /**/ // Retrieve all published Tutorials router.get( "/published" , tutorials.findAll); router.get( "/userIsOk" , userinfos.findAlluserIsOk); // Retrieve a single Tutorial with id router.get( "/user/:id" , userinfos.userfindOne); router.get( "/:id" , tutorials.findOne); // Update a Tutorial with id router.put( "/:id" , tutorials.update); router.put( "/user/:id" , userinfos.userupdate); // Delete a Tutorial with id router.put( "/:id" , tutorials.deleteid); router.put( "/user/:id" , userinfos.userdeleteid); // Delete all Tutorials router.put( "/" , tutorials.deleteAll); router.put( "/user" , userinfos.userdeleteAll); //app.use('/api/tutorials', router); app.use( '/api/tutorials' ,router); }; export default routes; |
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
分类:
Ajax&JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2023-08-09 python: audio
2012-08-09 csharp DataTable and DataGridView delete a Row
2010-08-09 asp.net3.5 csharp Calendar 控件显示周次(1月周次问题)