#StackBounty: #mysql #node.js #mongodb #mongoose #sequelize.js mongoose Schema to sequelize model

Bounty: 50

I made one app with mongodb (mongoose as ODM) but now I want to work with MySQL (work obligation) so I took Sequelize module for that, but I really don’t understand how to convert my userSchema to user model with all its m├ęthodes (I’m working with passportJs for authentication, so I have some methods that I’m using for example setpassword …)

Here my userSchema (mongoose) that works perfectly.

var mongoose = require('mongoose');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var validator = require('node-mongoose-validator');
var Schema = mongoose.Schema;

var userSchema = new Schema({
    name: {
      type: String,
      maxlength: 50
    },
    mail: {
      type: String,
      required: true,
      maxlength: 50,
      index: {
        unique: true
      }
    },
    hash: String,
    salt: String,
    {
      collection: "user"
    }
);

userSchema.methods.setPassword = function(password) {
  this.salt = crypto.randomBytes(16).toString('hex');
  this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
};

userSchema.methods.validPassword = function(password) {
  var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
  return this.hash === hash;
};

userSchema.methods.generateJwt = function() {
  var expiry = new Date();
  expiry.setDate(expiry.getDate() + 7);

  return jwt.sign({
    _id: this._id,
    mail: this.mail,
    name: this.name,
    exp: parseInt(expiry.getTime() / 1000),
  }, process.env.JWT_SECRET); // secret code from .env
};

module.exports = mongoose.model('user', userSchema);

and here what I’ve tried with sequelize:

 var crypto = require('crypto');
    var jwt = require('jsonwebtoken');

    var User = sequelize.define('user', {
      name: Sequelize.STRING,
      mail: Sequelize.STRING,
      hash: Sequelize.STRING,
      salt: Sequelize.STRING


    });

    User.methods.setPassword = function(password) {
      this.salt = crypto.randomBytes(16).toString('hex');
      this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
    };

    User.methods.validPassword = function(password) {
      var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
      return this.hash === hash;
    };

    User.methods.generateJwt = function() {
      var expiry = new Date();
      expiry.setDate(expiry.getDate() + 7);

      return jwt.sign({
        _id: this._id,
        mail: this.mail,
        name: this.name,
        exp: parseInt(expiry.getTime() / 1000),
      }, process.env.JWT_SECRET); // DO NOT KEEP YOUR SECRET IN THE CODE!
    };


module.exports = User;

I did not test that because I need to develop one other part, but I need to know that do you think about that, I feel that its full of errors

Thank you in advance


Get this bounty!!!

#StackBounty: #node.js #sequelize.js Sequelize – Not quite getting the correct results from a many to many select

Bounty: 100

I’m fairly new to Sequelize, but not to SQL. But I’m really struggling with how to correctly get my results from a many to many relationship.

My Schema:
My Schema

So I need to get all the Sheets with a given vendor_id and a given chemical_id.

Here is my Sequelize that is close but not quite producing the right query.

GetVendorFiles: async function(args) {
            console.log('args: ', args);
            if (!args.vendor_id) {
                throw new Error('Invalid argument: vendor_id');
            }
            let chemical_id = '';
            let load_id = '';

            if (args.load) {
                // first get the load id
                load_id = await db.Load.findOne({
                    attributes: ['id'],
                    where: { value: args.load }
                }).then((r) => console.log('load id: ', r));
            } else if (args.chemical) {
                // first get the load id
                chemical_id = await db.Chemical.findOne({
                    attributes: ['id'],
                    where: { name: args.chemical }
                }).then((r) => {
                    return r.dataValues.id;
                });
            }

            return await db.Vendor.findOne({
                where: { id: args.vendor_id }
            }).then(async function(vendor) {
                // build the include block conditionally based on whether
                // a chemical or load was passed in
                const model =
                    load_id !== ''
                        ? db.Load
                        : chemical_id !== ''
                        ? db.Load
                        : db.Sheet;
                const includeBlock = load_id
                    ? [
                            {
                                model: db.Load,
                                as: 'loads',
                                where: { id: load_id }
                            }
                      ]
                    : chemical_id
                    ? [
                            {
                                model: db.Chemical,
                                as: 'chemicals',
                                where: { id: chemical_id }
                            }
                      ]
                    : [];
                const files = await db.Sheet.findAll({
                    attributes: ['sheet_name', 'sheet_file_name'],
                    include: includeBlock,
                    model: model,
                    where: {
                        deleted_at: null,
                        vendor_id: vendor.dataValues.id
                    }
                });
                if (files) {
                    return files;
                }
                return null;
            });
        },

And here is the query it is producing:

SELECT `Sheet`.`id`, `Sheet`.`sheet_name`, `Sheet`.`sheet_file_name`, `chemicals`.`id` AS `chemicals.id`, `chemicals`.`name` AS `chemicals.name`, `chemicals`.`created_at` AS `chemicals.created_at`, `chemicals`.`updated_at` AS `chemicals.updated_a
t`, `chemicals`.`deleted_at` AS `chemicals.deleted_at`, `chemicals`.`created_at` AS `chemicals.createdAt`, `chemicals`.`updated_at` AS `chemicals.updatedAt`, `chemicals`.`deleted_at` AS `chemicals.deletedAt`, `chemicals->chemicals_to_loads`.`created_at` AS `chemicals
.chemicals_to_loads.createdAt`, `chemicals->chemicals_to_loads`.`updated_at` AS `chemicals.chemicals_to_loads.updatedAt`, `chemicals->chemicals_to_loads`.`load_id` AS `chemicals.chemicals_to_loads.load_id`, `chemicals->chemicals_to_loads`.`chemical_id` AS `chemicals.
chemicals_to_loads.ChemicalId` FROM `sheets` AS `Sheet` INNER JOIN ( `chemicals_to_loads` AS `chemicals->chemicals_to_loads` INNER JOIN `chemicals` AS `chemicals` ON `chemicals`.`id` = `chemicals->chemicals_to_loads`.`chemical_id`) ON `Sheet`.`id` = `chemicals->chemi
cals_to_loads`.`load_id` AND (`chemicals`.`deleted_at` IS NULL AND `chemicals`.`id` = 24) WHERE (`Sheet`.`deleted_at` IS NULL AND (`Sheet`.`deleted_at` IS NULL AND `Sheet`.`vendor_id` = '157'));

Towards the end it says ON Sheet.id = chemicals->chemicals_to_loads.load_id and I learned I simply need to change that Sheet.id to Sheet.load_id and everything works perfect! But how do I get the Sequelize to do that?

Update: Here is some troubleshooting I have done to try and fix it but to no avail. I thought I might need to properly define the foreign key in the Sheets table. So in my index.js under models where I am doing a lot of my associations, I added the foreignKey option to this line:

// Sheets- foreign key in sheets table "belongs to" loads table
db.Sheet.belongsTo(db.Load, { foreignKey: 'load_id' });

Unfortunately, that did not seem to have any effect.


Get this bounty!!!

#StackBounty: #node.js #google-cloud-platform #docker-compose #sequelize.js #google-cloud-sql Sequelize.authenticate() do not working (…

Bounty: 100

I am building api server with typescript ,express and Sequelize.

This is my database connection class.

export class Database {
  private _sequelize: Sequelize;
  private config: DBConfigGroup = dbConfig;
  private env = process.env.NODE_ENV as string;

  constructor() {
    this._sequelize = new Sequelize({
      dialect: 'postgres',
      database: this.config[this.env].database,
      username: this.config[this.env].username,
      password: this.config[this.env].password,
      host: this.config[this.env].host,
    });
  }

  async connect(): Promise<void> {
    try {
      console.log('start connect');
      await this._sequelize.authenticate();
      console.log('Connection has been established successfully.'.green.bold);
    } catch (error) {
      console.error('Unable to connect to the database:'.red.bold, error);
    }
  }

  async close(): Promise<void> {
    try {
      await this._sequelize.close();
      console.log('Connection has been close successfully.'.red.bold);
    } catch (error) {
      console.error('Unable to close to the database:'.yellow.bold, error);
    }
  }

  get sequelize(): Sequelize {
    return this._sequelize;
  }
}

So in my server.ts, i was calling this

dotenv.config({
  path: './config/environments/config.env',
});

const database = new Database();
console.log('Init db');
database
  .connect()
  .then(() => {
    console.log('success db ininit');
  })
  .catch((err) => {
    console.log('fail db init: ', err);
  }); 

/**
 * Server Activation
 */
const server = app.listen(PORT, () => {
  console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold);
});

So everythings works fine in my local development

But when i try to run it with docker compose with this config

// docker-compose.yml
version: '3.4'

services:
  api:
    stdin_open: true
    tty: true
    build:
      context: ./api
      dockerfile: Dockerfile.dev
    ports:
      - "5000:5000"
    volumes:
      - /app/node_modules
      - ./api:/app

This is my Dockerfile.dev file

FROM node:alpine

ENV NODE_ENV=development

WORKDIR /app

EXPOSE 5000

COPY package.json package-lock.json* ./ 

RUN npm install && npm cache clean --force

COPY . .

CMD ["npm", "run", "dev:docker"]

But the problem is when i run docker-compose up --build

I only see these logs

api_1  | Init db
api_1  | start connect
api_1  | Server running in development mode on port 5000

So basiccally there is no response whether sequelize.authenticate() is success or fail,
just Server running in development mode on port 5000 log out and nothing after all.

Why don’t it works inside docker like in the local, any config that i missed?

Thanks


Get this bounty!!!

#StackBounty: #node.js #sequelize.js #sequelize-cli sequelize-cli returning 'Unknown arguments' error

Bounty: 50

In my SailsJS app, when I enter the command into the terminal:

sequelize db:seed:all

I get the response:

Unknown arguments: models, username, password, database, host, dialect

Also when I run:

sequelize -v

I get back:

Sequelize CLI [Node: 6.2.1, CLI: 3.2.0, ORM: 4.28.6]

WARNING: This version of Sequelize CLI is not fully compatible with 
Sequelize v4. https://github.com/sequelize/cli#sequelize-support

I am connected to the db and I am able to run my app as well as update the db from the client. The problems seems to be totally restricted to Sequelize/Sequelize-CLI.


Get this bounty!!!

#StackBounty: #node.js #postgresql #sequelize.js Sequelize on NodeJS/ExpressJS return an error when running CLI command db:migrate

Bounty: 50

I’m following this tutorial Using PostgreSQL and Sequelize to persist our data on medium, and right now I’m stuck at the db:migrate. it’s returning this error

Sequelize CLI [Node: 12.1.0, CLI: 5.4.0, ORM: 5.8.2]

Loaded configuration file "config.json".
Using environment "development".

ERROR: Error parsing url: undefined

as you can see I’m using NodeJS version 12.1.0 and Sequelize CLI version 5.4.0 and Sequelize version 5.8.2 and all of them were the latest version.

and before running sequelize db:migrate, I’m running this command first SET DATABASE_URL=postgresql://[user[:password]@][netlocation][:port][/dbname] and it does not returns any error.

but it’s returning error after I ran db:migrate

I already tried to find the problem, but I can’t found the answer yet.
Here is my ./Models/Index.js file.

'use strict';

require('dotenv').config();

import { readdirSync } from 'fs';
import { basename as _basename, join } from 'path';
import Sequelize from 'sequelize';
const basename = _basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../../config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

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

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

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

export default db;

if you realize I just changed it to ES6 format which change some codes, but before I change it to ES6, it doesn’t work either. and for all the rest of the files I following the tutorial.

Here are the files that I think have a connection:

.env

DATABASE_URL=postgres://postgres:admin@localhost:5432/test_app

.sequelizerc

const path = require('path');

module.exports = {
  "config": path.resolve('./config.json'),
  "models-path": path.resolve('./app/Models'),
  "migrations-path": path.resolve('./migrations')
};

config.json

{
  "development": {
    "use_env_variable": "DATABASE_URL"
  },
  "test": {
    "use_env_variable": "DATABASE_URL"
  },
  "production": {
    "use_env_variable": "DATABASE_URL"
  }
}

If there are some files that I haven’t included yet please tell me, and please help me to fix find the solution for this problem. Thank you

OS: Windows 10


Get this bounty!!!