我的数据库使用nodejs、express框架和mysql。 我想知道如何使用 mysql 复制这个猫鼬代码。我找不到在 nodejs 文件中写入 sql 模式的方法。我必须为此使用工作台吗?谢谢!
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
local: {
username: String,
password: String
}
});
module.exports = mongoose.model('User', userSchema);
您可以使用以下任何一个:
书架
膝盖
反对
奥姆
续集
查看两者之间的比较:
https://npmcompare.com/compare/bookshelf,knex,objection,orm,sequelize
本教程也许可以帮助您使用“sequelize”: 使用 Angular、Express 和 MySQL 创建基于角色的用户身份验证系统
MySQL 没有像 Mongoose 这样的内置模式定义语言,因此您必须使用 SQL 查询手动创建表。
注意必须在顶部需要 mysql2 并安装它 npm i mysql2 : const mysql = require('mysql2/promise');
步骤:01 创建池连接
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'your_database_name'
});
步骤:02 创建用户表的函数
async function createUserTable() {
const connection = await
pool.getConnection();
try {
// Create user table
await connection.query(`
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL
)
`);
console.log('User table created successfully');
} catch (error) {
console.error('Error creating user table:', error);
} finally {
connection.release();
}
}
步骤:03 调用函数创建用户表
createUserTable();