Saturday, 22 August 2020

mongoose Schema to sequelize model

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



from mongoose Schema to sequelize model

No comments:

Post a Comment