glibaudio
glibaudio

Reputation: 83

Connect an existing MySQL db for a Node/Express app using Sequelize

Working on a project for a complete rewrite of an RoR to Node/Sequelize/Express/Angular app.

I have executed the old schema on my local machine and can view the db, tables and data OK.

Within my Node code I need to connect the existing DB.

I am following this tutorial: http://redotheweb.com/2013/02/20/sequelize-the-javascript-orm-in-practice.html

My question arrises when using sequelize.import and pointing it a directory.

  1. Should this be my local MySQL directory where the schema was set up? (assuming yes)
  2. Does model refer to the table in the DB?

Advice on how to correctly access the existing relational mapping is helpful.

This if my first question on Stack, thank you in advance.

var express = require('express');
var http = require('http');
var path = require('path');
var config = require('./config/config');

var Sequelize = require('sequelize');

var app = express();

var db = new Sequelize('somedb', 'root', 'password');

var models = [
  'users'
];

models.forEach(function(model){
  module.exports[model] = sequelize.import(__dirname + '/' + )
})

Upvotes: 1

Views: 1688

Answers (1)

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28798

Sequelize.import CANNOT import your current SQL schemas. You will need to write javascript code to define your models:

// in models/users.js
module.exports = function(sequelize, DataTypes) {
    return sequelize.define('User', {
        first_name: DataTypes.STRING,
        last_name: DataTypes.STRING,
    });
};

Assuming the script you posted is the root and there is a folder named models with a file users.js in the same directory, then the script will work. The path you pass to .import is the file system path of the javascript file that defines your model

Upvotes: 1

Related Questions