GithubHelp home page GithubHelp logo

sequelize / express-example Goto Github PK

View Code? Open in Web Editor NEW
2.5K 92.0 775.0 119 KB

A proposal for the usage of Sequelize within an Express.JS application.

License: MIT License

JavaScript 100.00%
sequelize boilerplate example documentation

express-example's Issues

Migrations and model syncing

Hey there. Thanks for the project. Can you explain why you have both migrations for setting up table schema and model syncing?
Thanks!

404 Not Found for new routes

Hi, I'm finding this very helpful :)

I am not familiar with "Jade" and would rather just explorer the queries output directly.

However, I continually get a 404 not found.

How can I fix this?

router.get('/users', function(req, res) {
  models.Users.findAll({}).then(function(users) {
    res.json(users);
  });
});

``

how to use DataType from req.body

Hi all, I'm struggling around that thing. Basically, in my sql table, I have FLOAT and other types and in my req.body all the value are string (even 'null') as they should be. Can't figure out a way to convert them before call model.update. JSON.parse(req.body) breaks everything.

My request configuration comes from:

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(fileUpload());

Thanks for any suggestion.

cannot read 'prototype' of undefined

EDIT: 7 minutes after posting this, ofcourse i find the solution by simply logging 'models' in the model. Yes, my table is called 'posters' and the model 'Poster'. But the models variable holds the table name. RESOLVED

EDIT2: So I received a notification that there was a reply and my answer isn't very clear. Just to make sure it's clear for you guys, I will clarify it a bit:
So in my database I had my table named 'posterParts', so first letter lower case and plural. My model (schema/models) for Sequelize was named 'PosterPart' with the first letter capital and singular. in the code I was calling the 'PosterPart' (models.PosterPart) but I had to call the name defined in the database, so models.posterParts. This is more a mistake on my side and I would suggest naming your database tables the same as you name your models to not run in problems like mine.

----- Original question:
I'm trying to get sequelize working with GraphQL in an express server, but I'm running into a problem. Sequalize on its own is working perfectly, but now I found this example to seperate models in seperate files. Of course I want that!

I tried to implement it exactly as it's done in this example, but it fails at this piece in models/index.js:

Object.keys(db).forEach((modelName) => {
  if ('associate' in db[modelName]) {
    db[modelName].associate(db);
  }
});

with the following error:

(...)/node_modules/sequelize/lib/associations/mixin.js:12
    if (!target.prototype || !(target.prototype instanceof this.sequelize.Model)) {
               ^

TypeError: Cannot read property 'prototype' of undefined

Since it uses the 'associate' from the model, I will include the setup of my model too:

export default (sequelize, DataTypes) => {
  const Poster = sequelize.define('posters', {
    title: DataTypes.STRING,
  });

  Poster.associate = (models) => {
    Poster.hasMany(models.PosterPart, {
      foreignKey: 'id',
    });
  };

  return Poster;
};

Now after a lot of debugging I initially thought using es6 syntax might be breaking it, so I tried to change all es6 syntax to be exactly as in this example, but it's still breaking. I get the following error:

I also thought that maybe the foreignKey: 'id' was causing issues, but that also don't seem to be the case.

Am I missing something obvious or is this a bug? I will revert to just using one big file for all models for now. But I would like to implement seperate models in the future, when the project is getting bigger.

Why export Sequelize?

I currently do not understand why Sequelize is exported in ./models/index.cs

db.Sequelize = Sequelize;

module.exports = db;

I do not see it used anywhere and from my current understanding, i do not know why it is exported here.
PS: I´m quite new to sequelize and i´m trying to understand the sample.

Thanks in advance

npm install error

npm install error
system: macOS 10.13.6
Node: 10.12.0
error info:

~/Documents/GitHub/express-example ⮀ ⭠ master ⮀ npm i
npm WARN deprecated [email protected]: This version is no longer maintained. Please upgrade to the latest version.
npm WARN deprecated [email protected]: This version is no longer maintained. Please upgrade to the latest version.
npm WARN deprecated [email protected]: This version is no longer maintained. Please upgrade to the latest version.

> [email protected] install /Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3
> node-pre-gyp install --fallback-to-build

node-pre-gyp ERR! Tried to download(403): https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v3.1.13/node-v64-darwin-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for [email protected] and [email protected] (node-v64 ABI) (falling back to source compile with node-gyp)
node-pre-gyp ERR! Tried to download(undefined): https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v3.1.13/node-v64-darwin-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for [email protected] and [email protected] (node-v64 ABI) (falling back to source compile with node-gyp)
  ACTION deps_sqlite3_gyp_action_before_build_target_unpack_sqlite_dep Release/obj/gen/sqlite-autoconf-3150000/sqlite3.c
  ACTION deps_sqlite3_gyp_action_before_build_target_unpack_sqlite_dep Release/obj/gen/sqlite-autoconf-3150000/sqlite3.c
  TOUCH Release/obj.target/deps/action_before_build.stamp
  TOUCH Release/obj.target/deps/action_before_build.stamp
  CC(target) Release/obj.target/sqlite3/gen/sqlite-autoconf-3150000/sqlite3.o
  CC(target) Release/obj.target/sqlite3/gen/sqlite-autoconf-3150000/sqlite3.o
rm: ./Release/.deps/Release/obj.target/sqlite3/gen/sqlite-autoconf-3150000/sqlite3.o.d.raw: No such file or directory
make: *** [Release/obj.target/sqlite3/gen/sqlite-autoconf-3150000/sqlite3.o] Error 1
gyp ERR! build error
  LIBTOOL-STATIC Release/sqlite3.a
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (events.js:182:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:240:12)
gyp ERR! System Darwin 17.7.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "build" "--fallback-to-build" "--module=/Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3/lib/binding/node-v64-darwin-x64/node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=/Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3/lib/binding/node-v64-darwin-x64"
gyp ERR! cwd /Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3
gyp ERR! node -v v10.12.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3/lib/binding/node-v64-darwin-x64/node_sqlite3.node --module_name=node_sqlite3 --module_path=/Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3/lib/binding/node-v64-darwin-x64' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:182:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:962:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
node-pre-gyp ERR! System Darwin 17.7.0
node-pre-gyp ERR! command "/usr/local/bin/node" "/Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3
node-pre-gyp ERR! node -v v10.12.0
node-pre-gyp ERR! node-pre-gyp -v v0.6.38
node-pre-gyp ERR! not ok
Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3/lib/binding/node-v64-darwin-x64/node_sqlite3.node --module_name=node_sqlite3 --module_path=/Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3/lib/binding/node-v64-darwin-x64' (1)
  CXX(target) Release/obj.target/node_sqlite3/src/database.o3~install: Failed to exec install script
error: error reading '../src/database.cc'cycle [email protected]~install: Failed to exec install script
1 error generated.
make: *** [Release/obj.target/node_sqlite3/src/database.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (events.js:182:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:240:12)
gyp ERR! System Darwin 17.7.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "build" "--fallback-to-build" "--module=/Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3/lib/binding/node-v64-darwin-x64/node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=/Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3/lib/binding/node-v64-darwin-x64"
gyp ERR! cwd /Users/fredxiao/Documents/GitHub/express-example/node_modules/sqlite3
gyp ERR! node -v v10.12.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/fredxiao/.npm/_logs/2019-01-25T04_56_23_629Z-debug.log
 ✘ ⮀ ~/Documents/GitHub/express-example ⮀ ⭠ master ⮀ node --version
v10.12.0
 ~/Documents/GitHub/express-example ⮀ ⭠ master ⮀

想问下

migrations 这个文件夹的作用是什么

ES5 syntax

It's almost 2017, why all still use ES5 syntax?

Error message when trying to configure database.

Hello, I'm just beginning with Sequelize, and I'm getting this error message:

Error: The dialect mysql is not supported. (Error: Please install mysql package manually)

I have mysql installed using MAMP on my Mac, and according to it, everything is working as it should.

When I trace out my config, it looks like this:

{ username: 'root',
password: 'root',
database: '_dev',
host: 'localhost',
dialect: 'mysql' }

Which looks ok to me.

Any thoughts on what is happening?

Thanks.

Dealing with multiple associations

I have asked a question in the main sequelize github, but as I am using the structure that is displayed in the express-example with a slightly older version of index.js, I tought it might be appropriate to reference it here: #3736

Migrations not correct

Hey guys,

I've just tried your sample and used the config to test the migrations and the hasMany and hasOne options against a postgres database. Right now I'm stuck because if one's not using your "sync" magic function, like in a productive environment, you're set off to investigate into undocumented parts of sequelize.

Could you possibly provide an example using a postgres database and a simple example of a dependency like this user/tasks list?

I'd be grateful for that!

run npm test failed

$NODE_ENV = test
mocha test/integration/*.test.js

  user creation page
Executing (default): TRUNCATE `Tasks`
Executing (default): TRUNCATE `Users`
    1) "before each" hook for "loads correctly"


  0 passing (99ms)
  1 failing

  1) user creation page "before each" hook for "loads correctly":
     SequelizeDatabaseError: ER_TRUNCATE_ILLEGAL_FK: Cannot truncate a table referenced in a foreign key constraint (`database_test`.`tasks`, CONSTRAINT `tasks_ibfk_1` FOREIGN KEY (`UserId`) REFERENCES `database_test`.`Users` (`id`))
      at Query.formatError (node_modules/sequelize/lib/dialects/mysql/query.js:175:14)
      at Query._callback (node_modules/sequelize/lib/dialects/mysql/query.js:49:21)
      at Query.Sequence.end (/Users/hugo/programming/github/_me/node-samples/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
      at Query.ErrorPacket (/Users/hugo/programming/github/_me/node-samples/node_modules/mysql/lib/protocol/sequences/Query.js:94:8)
      at Protocol._parsePacket (/Users/hugo/programming/github/_me/node-samples/node_modules/mysql/lib/protocol/Protocol.js:280:23)
      at Parser.write (/Users/hugo/programming/github/_me/node-samples/node_modules/mysql/lib/protocol/Parser.js:73:12)
      at Protocol.write (/Users/hugo/programming/github/_me/node-samples/node_modules/mysql/lib/protocol/Protocol.js:39:16)
      at Socket.<anonymous> (/Users/hugo/programming/github/_me/node-samples/node_modules/mysql/lib/Connection.js:96:28)
      at readableAddChunk (_stream_readable.js:146:16)
      at Socket.Readable.push (_stream_readable.js:110:10)
      at TCP.onread (net.js:523:20)

Add seed data

If the purpose of this repo is providing a sample sequelize project, it will be beneficial if you add seed examples.

Sqlite and running tests

There is an error when you run npm test for the first time (before running server), saying that tables are not created?

Fail to run on Heroku

Hi @sdepold, I did a node app with mySql based on your app. I used the same index.js from models, so the tables will be generated automatically once server is on. It works perfectly locally. The heroku app uses ClearDB as database and the connection is find. However, it just hangs on Heroku and no table is generated. I have created a post on Stackoverflow. Or you can check out my repo. I could really use some help! Thanks!!!

jade tasks

There seems to be an issue with line 24 of index.jade "each task in user.tasks" which seems to be related with the fact that "user.tasks" is not well defined. Maybe something must be changed in routes/index.js? I don't know but I keep getting a 500 error when I try submitting a new user: "Cannot read property 'length' of undefined" (when I comment from line 24, everything else works well)

Wrong API on migrations

Hi, I'm just starting with Sequelize, and looks like a great library!.

Using the sample project, just found out that the migrations API used is not correct, I guess is something still not migrated since the project start using umzug (I suppose)

file: 20141003120222-create-user.js

Current (wrong) API:

up: function(migration, DataTypes, done) {
    migration
      .createTable('Users', {
        username: DataTypes.STRING
      })
      .complete(done)
  },

Expected (correct) API:

up: function(queryInterface, Sequelize) {
    queryInterface
      .createTable('Users', {
        username: Sequelize.STRING
      });
  },

If needed, I can create the pull request with the changes.

Again, great work guys, kudos!!

More documenation!

As a node beginner, it's not immediately clear to me why things are the way they are in this repo. I would love some explanations behind these architectural decisions :)

Association via classMethods doesn't work

Have been unable to associate models with each other.
classMethods: { associate: (models) => { Users.hasMany(models.customers, { foreignKey: 'user_id' }) } }

Any idea what I'm missing?

Thanks!

Named association table with own attributes does not work

Hi!

I tried to switch a project of mine to the way you handle the models in this example. It works fine except for a named association table which has own attributes (id and quantity):

https://gist.github.com/bkimminich/2393729806b07e9f1ff6

The table gets created but does not receive the ProductId and BasketId fields. Instead an additional BasketsProducts table is created alongside. Of course this cannot work.

Do you have any idea how to deal with this issue? I'd be happy for every hint... 👍

Add scopes

I really like how you separate your models file thanks to the ./models/index file.
But, how can you configure the scopes on a model with this pattern?

Heres' an example of my problem:

'use strict';

module.exports = function (sequelize, DataTypes) {
  var Project = sequelize.define('project', {
    name: { type: DataTypes.STRING },
  }, {
    scopes: {
      myAwesomeScope: {
        include: [models.user]  // <-------- how can I retrieve here the models.user?
      }
    },
    classMethods: {
      associate: function (models) {
        Project.hasMany(models.user);
      }
    }
  });

  return Project;
};

User model goes by the actual table name or model name?

Hi,
On the production floor (my workplace, proj is still pending development), I added new route directly to your app. Here how I tried with Assembly model

// model schema
"use strict";

module.exports = function(sequelize, DataTypes) {
  var Assembly = sequelize.define('orm_assembly_table', {
      customer_id: {
        type: DataTypes.INTEGER.UNSIGNED,
        allowNull: false
      },
      number: DataTypes.STRING(250),
      revision: DataTypes.STRING(10),
      unique_key: {
        type: DataTypes.STRING(10),
        allowNull: false,
        unique: true
      }
    },
    {
      timestamps: false,
      freezeTableName: true

      /*, getterMethods   : {
       fullName       : function()  { return this.firstname + ' ' + this.lastname }
       },

       setterMethods   : {
       fullName       : function(value) {
       var names = value.split(' ');

       this.setDataValue('firstname', names.slice(0, -1).join(' '));
       this.setDataValue('lastname', names.slice(-1).join(' '));
       },
       },
       classMethods: {
       generateHash : function(password) {
       return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
       },
       },
       instanceMethods: {
       validPassword : function(password) {
       return bcrypt.compareSync(password, this.localpassword);
       }
       }

       */
    });

  return Assembly;
};
extends layout

block content
  h1= title
  p This is Sequelize greeting you :)

  h2 Assembly Listing

  ul
  each assembly in assemblys
    li
      = assembly.number
      | &nbsp;
      | (
      a(href="/users/" + assembly.revision + "/destroy") Destroy
      | )
var models  = require('../models');
var express = require('express');
var router  = express.Router();

router.get('/', function(req, res) {
  models.orm_assembly_table.findAll().then(function(assemblys) {
    res.render('assembly', {
      title: 'Sequelize: Express Example',
      assemblys: assemblys
    });
  });
});

module.exports = router;

If all go like this, I get assemblys displayed correctly.

When I tried with Assembly in place of (au lieu de) orm_assembly_table, I encountered error of undefined. So, in a router.get(), what should be used as property of models? I tried console.log(models) the models object in models/index.js and saw something like

models: { orm_assembly_table: orm_assembly_table }

 importCache: { 'C:\inetpub\wwwroot\development\phuc_NodeJS_MySQL\NodeMySQL\models\assembly.server.mod
el.js': orm_assembly_table }

Advices? Thanks

P/S: I like to write it models.Assembly than the actual table name (orm_assembly_table, which is not nice) but I can't get it to work.

Sequelize-cli creates nothing

Hello!

I'm following your tuto on README, however when I run sequelize model:create, it generates nothing: neither model and migration.

$ sequelize model:create --name User --attributes name:string, latitude:float, longitude:float

Output:

Sequelize [Node: 5.6.0, CLI: 2.3.1, ORM: 3.21.0]

Loaded configuration file "config/config.json".
Using environment "development".
Using gulpfile /usr/local/lib/node_modules/sequelize-cli/lib/gulpfile.js

Thanks in advance!

Packaging with Electron

I use the same approach. I use sequelize with Electron, the problem is, when I package my app, it throws an error saying that models directory is not defined. How do you handle that?

Theoretically, I am thinking that if I simply import them and attach them to db it should work, but I actually have to use sequelize['import']() for that do I? since I bundle all my files I should just import all my models then attach them to db.

import fs from 'fs';
import path from 'path';
import sequelize from '../main_process/Database';
import Sequelize from 'sequelize';

let basename = path.basename(__filename);
let db = {};

fs.readdirSync(__dirname)
.filter(function(file) {
  return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
  let model = sequelize['import'](path.join('../../', __dirname, file));
  db[model.name] = model;
});

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

Starter kit not suited for newbies

I write something here in hope that someone reads it.

I'm fairly new to developping in general, but I'm able to learn on my own.

Anyway it was a really difficult task for me to learn how to use sequelize for several reasons. The 'getting started' link in the docs never allowed me to get started... Then i came across the express-example that i had to debug for 3 days to really understand how everything worked.

What i'm getting at is this : i have written a very minimalist app to help understand how sequelize work with node/express and very minimal frontend (html/css/js). I also commented to explain everything inside. I hope to share it with everyone if they're interested.

The express example is very hard to understand, not to mention that jade is deprecated (as it is said during the npm install). And i'm sure that like me a lot of people learn frontend development, then backend (node in our case) so they never heard of jade/pug/ejs/ember templating. I didn't learn any of them and I just checked an article saying that AoT compilation tend to make server side templating less important...

In no way i am saying that the work put in the sequelize docs or the express-example is bad, maybe not tailored to people trying node/express/sql for the first time.

Thanks for reading.

How to update one object and get updated object as result?

I update a user model like that

db.user.update({
            display_name: body.display_name,
            type: body.type,
            uri: body.uri,
            href: body.href,
            email: body.email,
            token: token,
            country: body.country,
          }, {
            returning: true,
            plain: true,
            limit: 1,
            where: {
                id: body.id
            }
        })

and I get a result:

[
  null,
  {
    "id": "asdasdasd",
    "display_name": "Michu",
    "type": null,
    "uri": "asdsd:asdasda",
    "href": "http://skadsda.pl",
    "email": "[email protected]",
    "country": "PL",
    "createdAt": "2017-01-10T20:53:29.665Z",
    "updatedAt": "2017-01-11T16:29:06.591Z",
    "token": "eyJhbGciOiJIUzI1NiJ9.YXNkYXNkYXNk.rpEOsO5er5KHG3g7K9EAHWAMphOyxFsx-s1gtMJ4cAw"
  }
]

I want to get :

{
    "id": "asdasdasd",
    "display_name": "Michu",
    "type": null,
    "uri": "asdsd:asdasda",
    "href": "http://skadsda.pl",
    "email": "[email protected]",
    "country": "PL",
    "createdAt": "2017-01-10T20:53:29.665Z",
    "updatedAt": "2017-01-11T16:29:06.591Z",
    "token": "eyJhbGciOiJIUzI1NiJ9.YXNkYXNkYXNk.rpEOsO5er5KHG3g7K9EAHWAMphOyxFsx-s1gtMJ4cAw"
  }

How to reach that simple stuff?!

'sequenlize' is not recognized

I've followed installation steps mentioned in README.md file.

But when I run command

sequelize init

it throws an error,

'sequenlize' is not recognized as an internal or external command, operable program or batch file.

Add Heroku defaults

Please change models/index.js to intelligently integrate to heroku production database as default in production environment without any tweaks.

 heroku addons:add heroku-postgresql:dev 

By just typing this code to the command line production app should intelligently connect to the database. Is there any good examples of this? I've found the sequelize documentation too hacky.

Setup not working

I'm on windows 10, node v6.11.3, npm v5.3.0

I get the following error

B:\Folder\dbtest>npm install --save sequelize sequelize-cli sqlite3
npm ERR! path B:\Folder\dbtest\node_modules\js-beautify\js\bin\html-beautify.js
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall chmod
npm ERR! enoent ENOENT: no such file or directory, chmod 'B:\Folder\dbtest\node_modules\js-beautify\js\bin\html-beautify.js'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

while running the command npm install --save sequelize sequelize-cli sqlite3

Instructions to fire up the app

Hi,

Can you please off some instructions in your readme on how to boot the app?

So far I have cloned the repo, ran npm install, and installed all the grunt packages.

My error (below) suggests something to related to nodemon - - - which leads me to believe that the issue is related to booting mysql before running grunt on the root directory of the app. Its probably an easy answer. I apologize for my newbie question in advance.

Any help you can offer would be greatly appreciated.

All the best,

Ben McFerren

$ grunt
Running "concurrent:tasks" (concurrent) task
Running "watch" task
Waiting...Running "nodemon:dev" (nodemon) task

Usage: nodemon [options] [script.js] [args]

Options:

-e, --ext extensions to look for Example: ".js|.html|.css"
-x, --exec app execute script with "app", ie. -x "python -v"
-q, --quiet minimise nodemon messages to start/stop only
-w, --watch dir watch directory "dir". use once for each
directory to watch
-I, --no-stdin don't try to read from stdin
-d, --delay n throttle restart for "n" seconds
-L, --legacy-watch Forces node to use the most compatible
version for watching file changes
--exitcrash exit on crash, allows use of nodemon with
daemon tools like forever.js
-v, --version current nodemon version
-h, --help you're looking at it

Note: if the script is omitted, nodemon will try to
read "main" from package.json and without a .nodemonignore,
nodemon will monitor .js, .coffee, and .litcoffee by default.

Examples:

$ nodemon server.js
$ nodemon -w ../foo server.js apparg1 apparg2
$ PORT=8000 nodemon --debug-brk server.js
$ nodemon --exec python app.py

For more details see http://github.com/remy/nodemon/

Done, without errors.

Support automatic model configuration with webpack

I'm talking about the index.js file under models that reads it's directory and finds all the other models to incorporate into the current db instance.

I'm trying to get it to work with babel+webpack, but since after compilation the working directory (__dirname) no longer has those models, the index.js file is unable to find them.

So I've had to use the following less than ideal solution to manually insert my models:

import Sequelize from 'sequelize';

import { ENV } from '../../config';
import sequelizeConfig from '../sequelize_config.json';
import userModel from './user';

const config = sequelizeConfig[ENV];

const db = {};

const dbUrl = process.env[config.use_env_variable];

const { database, username, password } = config;

const sequelize = dbUrl
  ? new Sequelize(dbUrl)
  : new Sequelize(database, username, password, config);

db.User = sequelize.import('User', userModel);
sequelize.sync();

Object.keys(db).forEach((modelName) => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

export { db as Models, sequelize };

Obviously, I'd prefer not to have to do this manually for every model I add. Is there a way to make automatic model detection work with webpack? (Here's my webpack config)

duplicate foreignKey when using sequelize.sync()

I'm using models like files in models folder. But when i'm using sequelize.sync() some models duplicated foreginKey like following

image

This is my associate

image

image

image

image

Have 3 foreginKey but sequelize has created 6 foreginKey. Anybody can help me? Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.