14

I am using nodejs, express framework and mysql for my database. I would like to know how can I replicate this mongoose code using mysql. I cannot find a way to write my sql schema in a nodejs file. Do I have to use workbench for this? Thanks!

var mongoose = require('mongoose');

var userSchema = mongoose.Schema({
    local: {
            username: String,
            password: String
         }
 });

module.exports = mongoose.model('User', userSchema);
5
  • check this: blog.ragingflame.co.za/2014/7/21/using-nodejs-with-mysql Commented Dec 2, 2015 at 9:53
  • One thing I don't really understand: why are you using Mongoose? If you enter Mongoose's site it clearly says: mongoose: elegant mongodb object modeling for node.js Commented Dec 2, 2015 at 10:14
  • @charliebrownie i was following a tutorial series where he used this code. But I like mysql better so thats why i was looking for an alternative. Commented Dec 2, 2015 at 12:36
  • Oh, all right, I thought you were trying to use mongoose on a MySQL database. In this case, you will have to use a MySQL driver like this one (node-mysql). Commented Dec 2, 2015 at 13:00
  • any luck with that? did you find any solution? Commented Sep 30, 2016 at 7:47

2 Answers 2

10

You can use any of:

  • bookshelf
  • knex
  • objection
  • form
  • sequelize

See this comparison between them:

This tutorial may help you to use sequelize: Creating a Role-Based User Authentication System with Angular, Express and MySQL

Sign up to request clarification or add additional context in comments.

2 Comments

its not working when I click that sequelize link.
This is Old training but if you want, can read it in: hisk.io/…
0

MySQL does not have a built-in schema definition language like Mongoose, so you'll have to create tables manually using SQL queries.

note must require mysql2 at top and install it npm i mysql2 : const mysql = require('mysql2/promise');

Step:01 Create a pool connection

const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'your_database_name'
});

Step:02 Function to create user table

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();
}

}

Step:03 Call the function to create the user table

createUserTable();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.