user.validatePassword is not a function - passport.js

var bcrypt = require('bcrypt-nodejs');
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define('user', {
email: DataTypes.STRING,
password: DataTypes.STRING,
status: DataTypes.INTEGER
}, {});
user.associate = function(models) {
// associations can be defined here
};
user.validPassword = function (password) console.log(this.password);
};
return user;
};
Getting this error in node js
I am using "sequelize": "^5.21.3",
"sequelize-cli": "^5.5.1"
enter image description here

It should be:
user.validPassword = function (password) { console.log(this.password) };
you are missing the curly braces.
or arrow function,
user.validPassword = password => console.log(this.password);
try this code:
'use strict';
var bcrypt = require('bcrypt-nodejs');
module.exports = (sequelize, DataTypes) => {
var user = sequelize.define('user', {
email: DataTypes.STRING,
password: DataTypes.STRING,
status: DataTypes.INTEGER
}, {});
user.associate = function (models) {
};
user.prototype.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};
return user;
};
hope this helps.

Related

Error("No Sequelize instance passed") No Sequelize instance passed

Hello can somebody help me with this ? I was doing my controllers and I can access to my model like this "const { User } = require("../models/User");" but than when I send my request I had this message "TypeError: Cannot read property 'create' of undefined" so something was missing.
So I change my call model to this "const { User } = require("../models");".
And I went on my model index.js (so connection sequelize) and I add fs function and Objectif.key. After all those changes I have the error "No Sequelize instance passed".
So maybe somebody can help with this because I don't see the problem
So this is my model index.js
//sequelize importe
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const db = {};
const basename = path.basename(__filename);
let sequelize = new Sequelize("groupomania", "root", "root", {
host: "localhost",
dialect: "mysql",
});
sequelize
.authenticate()
.then(() => {
console.log("Connection has been established successfully!");
})
.catch((err) => {
console.log("Can't establish database connection:\n" + err);
});
fs.readdirSync(__dirname)
.filter((file) => {
console.log( file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js");
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
This is my model User.js
const { Model } = require("sequelize");
module.exports = (Sequelize, DataTypes) => {
class User extends Model {
toJSON() {
return {
...this.get(),
password: undefined,
};
}
}
User.init(
{
id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 },
nom: { type: DataTypes.STRING, allowNull: false },
prenom: { type: DataTypes.STRING, allowNull: false },
email: {
type: DataTypes.STRING,
allowNull: false,
validate: { notNull: true, notEmpty: true, isEmail: true },
},
status: { type: DataTypes.STRING, allowNull: false },
password: { type: DataTypes.STRING, required: true },
},
{ Sequelize, tableName: "users", modelName: "User" }
);
return User;
};
My controllers/user.js
/*const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");*/
const { User } = require("../models/User");
module.exports.signup = async (req, res) => {
try {
const user = await User.create({
nom: "Jp",
prenom: "remy",
email: "remy#gmail.fr",
password: "motdepasse",
});
res.status(200);
throw Error("erreur est survenu");
} catch (erreur) {
console.log(erreur);
res.status(200).json({ erreur });
}
};
My route user
const express = require("express");
const router = express.Router();
const userCtrl = require("../controllers/user");
router.post("/signup", userCtrl.signup);
/*router.post("/login", userCtrl.login);*/
module.exports = router;
Thank you for any help! :)
The answer was that on my model user the "S" of sequelize must have an s minus

TypeError: Cannot read properties of undefined (reading 'create')

const express = require("express");
const router = express.Router();
const bcrypt = require("bcrypt");
const { Users } = require("../../models/Users");
router.post("/", async (req, res) => {
const { username, password } = req.body;
bcrypt.hash(password, 10).then((hash) => {
Users.create({
username: username,
password: hash,
});
res.json("SUCCESS");
});
});
models/Users.js
module.exports = (sequelize, DataTypes) => {
const Users = sequelize.define("Users", {
username: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
});
return Users;
};
Hello i have problem with creating user in my db. The error is TypeError: Cannot read properties of undefined (reading 'create'). I dont know what is wrong. Help me please.
Your models/Users.js module exports a function, not the Users object that you need. Instead of having sequelize and DataTypes as function parameters, you should require them in the module:
const {sequelize, DataTypes} = require("sequelize");
module.exports = {
Users: sequelize.define("Users", {
...
})
};

Sequelize model custom function cannot be called from controller

I have a sequelize model this custom functions like so:
'use strict';
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('../../config');
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.STRING,
primaryKey: true
},
name: DataTypes.STRING,
email: DataTypes.STRING,
bio: DataTypes.STRING,
phone: DataTypes.STRING,
username: DataTypes.STRING,
password: {
type: DataTypes.STRING,
set(value){
this.setDataValue('password', bcrypt.hashSync(value, 10));
}
}
}, {});
User.generateJWT = function(id, username) {
return jwt.sign({
id: id,
username: username,
expiresIn: config.auth.exp
}, config.secret);
};
User.toAuthJson = async function() {
return {
name: this.name,
email: this.email,
bio: this.bio,
phone: this.phone,
username: this.username
};
};
User.validatePassword = function(password, passwordHash){
return bcrypt.compareSync(password, passwordHash);
};
User.isUniqueEmail = async function(email) {
return await User.findOne({where: {email}}) === null;
};
User.isUniqueUsername = async function(username) {
return await User.findOne({where: {username}}) === null;
};
User.isUniquePhone = async function(phone) {
return await User.findOne({where: {phone}}) === null;
};
User.associate = function(models) {
// associations can be defined here
};
return User;
};
and a controller like so:
const {User} = require('../database/models/');
module.exports.register = async (req, res, next) => {
try {
const isUniqueEmail = await User.isUniqueEmail(req.body.email);
if (!isUniqueEmail) return res.status(422).json({'message': 'email already exists'});
const isUniquePhone = await User.isUniquePhone(req.body.phone);
if (!isUniquePhone) return res.status(422).json({'message': 'phone already exists'});
const isUniqueUsername = await User.isUniqueUsername(req.body.username);
if (!isUniqueUsername) return res.status(422).json({'message': 'username already exists'});
const user = await User.create(req.body);
console.log(user.toAuthJson()); //an error occurs here
return res.status(201).json({user: user.toAuthJson()});
}catch (e) {
next(e);
}
};
when i try to access the toAuthJson function from this controller like this user.toAuthJson. "notice the small u." it throws an error TypeError: User.toAuthJson is not a function. I should be able to access it normally. help. thanks
User.toAuthJson is currently a class method. Like with the other functions, you'd need to call it like User.toAuthJson(user).
You're probably looking for an instance method, so you'd want to define it in the prototype instead:
User.prototype.toAuthJson = function() {
return {
name: this.name,
email: this.email,
bio: this.bio,
phone: this.phone,
username: this.username
};
};
Now you can call it on a User instance, like you were attempting to do:
console.log(user.toAuthJson());
Notice also that I omitted the async since this function doesn't do anything asynchronous.

findAll() is not a function sequelize

I'm making an app with nodejs and I want to conect to my models but I keep getting the same error:
TypeError: user.findAll is not a function
routes/user.js
const express = require('express');
const router = express.Router();
const db = require('../config/database');
const user = require('../models/users');
router.get('/', (req, res) => user.findAll()
.then(users => {
console.log(users)
res.sendStatus(200);
})
.catch(err => console.log(err)));
module.exports = router;
models/user.js
'use strict';
const Sequelize = require('sequelize');
const db = require('../config/database')
module.exports = (sequelize, DataTypes) => {
const users = sequelize.define('users', {
id: DataTypes.INTEGER,
name: DataTypes.STRING,
age: DataTypes.INTEGER,
email: DataTypes.STRING,
country: DataTypes.STRING,
state: DataTypes.STRING,
city: DataTypes.STRING
}, {});
users.associate = function(models) {
// associations can be defined here
};
return users;
};
you should use db.users.findAll() instead of user.findAll(). it will work
I found out the error, I wasn't importing/exporting properly, I changed my models/user.js file to:
'use strict';
const Sequelize = require('sequelize');
const db = require ('../config/database')
const DataTypes = require('sequelize/lib/data-types')
const User = db.define('users', {
name: DataTypes.STRING,
age: DataTypes.INTEGER,
email: DataTypes.STRING,
country: DataTypes.STRING,
state: DataTypes.STRING,
city: DataTypes.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
};
module.exports = User

A is not associated to B

Looked on the internet about similar questions/errors, none of them helped me...
Unhandled rejection SequelizeEagerLoadingError: Task is not associated to User!
My users route
router.get('', function (req, res) {
models.User.findAll({
include: [
{
model: models.Task,
as: 'tasks'
}
]
}).then(function (users) {
res.send(users);
});
});
User model
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
email: DataTypes.STRING
}, {
underscored: true
});
User.associations = function (models) {
User.hasMany(models.Task, { as: 'tasks' });
};
return User;
};
Task model
'use strict';
module.exports = (sequelize, DataTypes) => {
const Task = sequelize.define('Task', {
name: DataTypes.STRING
}, {
underscored: true
});
Task.associations = function (models) {
Task.belongsTo(models.User);
};
return Task;
};
I associate them both, and made a bidirectional relationship..
As you are using the finder function for association with as option, Sequelize cannot find that alias, as it is not defined explicitly anywhere. Please try this one:
User.associations = function (models) {
User.hasMany(models.Task, { as: 'tasks' });
};
Hope this helps.

Resources