Im trying to validate a username and password to not be null when there is a post request made so that there are no empy rows, but I keep getting
Express server listening on port 5000
/Users/ra/Desktop/Jos/node_modules/sequelize/lib/dao-validator.js:216
throw new Error("Invalid validator function: " + validatorType)
^
Error: Invalid validator function: allowNull
heres the the employer model
'use strict';
var Sequelize = require('sequelize');
module.exports = function (sequelize) {
var Employer = sequelize.define("employer", {
username: { type: Sequelize.STRING, validate: { allowNull: false } },
password: { type: Sequelize.STRING, validate: { allowNull: false } }
});
return {
Employer: Employer
};
};
allowNull must be in field options, not in validator:
var Sequelize = require('sequelize');
'use strict';
var Sequelize = require('sequelize');
module.exports = function (sequelize) {
var Employer = sequelize.define("employer", {
username: { type: Sequelize.STRING, allowNull: false },
password: { type: Sequelize.STRING, allowNull: false }
});
return {
Employer: Employer
};
};
See doc here and comment of source code here
Before Sequelize 2.0 you could use notNull validator, but it was removed in 2.0 version (see 2.0 changes here)
Related
This is my user.js Sequelize class:
'use strict';
const {Sequelize} = require('sequelize');
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static init(sequelize) {
super.init(
{
name: Sequelize.STRING,
},
{
sequelize,
});
this.addHook('beforeSave', async (user) => {
return user.id = uuid();
});
return this;
}
static associate(models) {
// define association here
User.hasMany(UserRole,
{
foreignKey: {
field:'UserId',
allowNull: false,
},
});
}
}
User.init({
Id: DataTypes.UUID,
Name: DataTypes.STRING,
UserName: DataTypes.STRING,
Email: DataTypes.STRING,
Password: DataTypes.STRING,
PhoneNumber: DataTypes.STRING,
MobileNumber: DataTypes.STRING,
DateOfBirth: DataTypes.DATE,
LockoutEnabled: DataTypes.BOOLEAN,
LockoutEnd: DataTypes.DATE
}, {
sequelize,
modelName: 'User',
});
return User;
};
I am trying to declare an instance to do a findAll call to my db.
So far this is what I have and it keeps saying findAll is not a function:
const {Sequelize} = require('sequelize');
const {userModel}= require('../../models/user');
function GetAll(){
return user.findAll();
}
module.exports = {
GetAll,
}
I'm new to Express JS and even more so for Sequelize.
Look at the question and my answer here to figure out how to register models and associations.
You export a function that returns a registered model, so you need to call it first passing a Sequelize instance and DataTypes and then you can use the returned model to call a method like findAll. It's better to register all models first and only after that register all associations between them (see the mentioned link).
Thank you for taking the time to help out. When running my server I am getting a message "Executing (default): SELECT 1+1 AS result". My tables are not being created. How do I fix this error? I am using the technologies MySQL, Sequelize, JavaScript, Express, and Node.
Connection.js (I have checked the .env and the information is accurate)
const Sequelize = require('sequelize');
require('dotenv').config();
const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PW, {
host: 'localhost',
dialect: 'mysql',
port: 3306
});
module.exports = sequelize;
Schema.sql
DROP DATABASE IF EXISTS events_db;
CREATE DATABASE events_db;
Customer model
const { DataTypes, Model } = require('sequelize');
const sequelize = require('../config/connection');
class Customer extends Model {}
Customer.init(
{
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV1,
primaryKey: true,
allowNull: false,
unique: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true,
}
},
phone: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
notEmpty: true,
is: /^[\+]?[(]?\d{3}[)]?[-\s\.]?\d{3}[-\s\.]?\d{4,6}$/im
}
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
address: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
notEmpty: true
}
}
},
{
sequelize,
freezeTableName: true,
underscored: true,
modelName: 'customer'
}
);
module.exports = Customer;
Model index.js
const Customer = require('./Customer');
const Event = require('./Event');
const EventType = require('./EventType');
const Reservation = require('./Reservation');
Customer.hasMany(Reservation, {foreignKey: { allowNull: false }});
Event.hasMany(Reservation, {foreignKey: { allowNull: false }});
Event.hasOne(EventType, {foreignKey: { allowNull: false }});
Event.hasOne(Customer, {foreignKey: { allowNull: false }});
module.exports = { Customer, Event, EventType, Reservation };
Server.js
const express = require('express');
const sequelize = require('./config/connection');
const app = express();
const PORT = process.env.PORT || 3001;
const routes = require('./routes');
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.use(routes);
sequelize.sync({ force: false }).then(() => {
app.listen(PORT, () => {
console.log(`App is listening on port ${PORT}`);
});
});
Imported models into server.js file. Did not need to call the variable. This allowed for sequelize to "see" my models. When implementing a controller or GraphQL, this import can be removed.
I am learning to use sequelize with my Next.js app.I set up the sequelize, used the cli to generate migrations, created the model (user) , and when i try to test it, going to the http://localhost:3000/api/app . i get an error -> Cannot read property 'findAll' of undefined.
my model class is coming up as undefined. anyone has any idea?
*director structure
MyApp
...
> database
- db.js
> migrations
> models
-user.js
> node_modules
> pages
> api
- app.js
db.js
const Sequelize = require('sequelize');
const db = new Sequelize('mydb', 'root', 'pass', {
host: "localhost",
port: 3306,
dialect: 'mysql',
operatorsAliases:false,
logging: function () {},
pool: {
max: 5,
min: 0,
idle: 10000
},
dialectOptions: {
socketPath: "/var/run/mysqld/mysqld.sock"
},
define: {
paranoid: true
}
});
db.authenticate().then(() => {
console.log('connection error');
}).catch(err => {
console.log('Connection successful');
});
module.exports = db;
model/User.js
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define("User", {
id : {
type: DataTypes.INTEGER(11),
allowNull: false,
autoIncrement:true,
primaryKey:true
},
firstName : {
type: DataTypes.STRING(50),
allowNull: false
}
lastName : {
type: DataTypes.STRING(50),
allowNull: false
},
created: {
type: 'TIMESTAMP',
defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
allowNull: false
},
updated:{
type: 'TIMESTAMP',
defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
allowNull: false
}
});
return user;
};
pages/api/app.js
const models = require('../../models')
export default (req, res) => {
models.user.findAll(); //error => Cannot read property 'findAll' of undefined
};
You define uppercase User in the User.js file, so you have to use it uppercase:
const models = require('../../models');
export default async (req, res) => {
const users = await models.User.findAll();
console.log(users);
};
Here below code is sample MVC framework code in PHP. I need same process as like in node.js with mongoose also.
I'm using Node.js, MongoDB, REST API development.
controller file:
<?php
class Myclass {
public function store_users() {
//get the data from model file
$country = $this->country->get_country_details($country_id);
//After getting data do business logic
}
}
model file
<?php
class Mymodel {
public function get_country_details($cid) {
$details = $this->db->table('country')->where('country_id',$id);
return $details;
}
}
In node.js need to use as like MVC PHP process. Kindly suggest on this.
Lets say you have user schema in mongoose which should act as model
// userModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var user = new Schema({
name: { type: String, required: true },
dob: { type: Date },
email: { type: String, required: true, unique: true, lowercase: true},
active: { type: Boolean, required: true, default: true}
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
});
var userSchema = mongoose.model('users', user);
module.exports = userSchema;
// userController.js
var User = require('./userModel');
exports.getUserByEmail = function(req, res, next) {
var email = req.param.email;
User.findOne({ email: email }, function(err, data) {
if (err) {
next.ifError(err);
}
res.send({
status: true,
data: data
});
return next();
});
};
Ref: http://mongoosejs.com/docs/index.html
I am facing issue on connection of SEQUELIZE(mysql) with NodeJs. Though connection is established but models are not properly configured. I have use this approach --
./config/sequelize-conn.js
'use strict';
var sequelize = function (config, Sequelize) {
var sql = new Sequelize(config.mysql.db, config.mysql.user, config.mysql.pass, {
host: config.mysql.host,
dialect: 'mysql', //|'sqlite'|'postgres'|'mssql'
pool: {
max: 5,
min: 0,
idle: 10000
},
//logging: true,
underscored: true
});
sql
.sync({force: true})
//.authenticate()
.then(function () {
console.log('Connection has been established successfully with mysql.');
}, function (error) {
console.log('Connection with mysql failed.', error);
});
return sql;
};
module.exports = sequelize;
//server.js
var sequelize = require('sequelize');
var sqlConnection = require('./config/sequelize-conn')(config, sequelize);
I wish to directly use model this way ..
models/HotelGroup.js
var Sequelize = require('sequelize');
var sequelize = require('../../config/sequelize-conn');
var HotelGroup = Sequelize.define('hotel_chains', {
id: {
type: Sequelize.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
hotel_name: {
type: Sequelize.STRING,
allowNull: false
},
hotel_code: {
type: Sequelize.STRING,
allowNull: false
},
status: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: '1'
}
}, {
tableName: 'hotel_chains',
timestamps: false,
paranoid: true // Model tableName will be the same as the model name
});
module.exports = HotelGroup;
Its giving me error that sequelize.define is not a function.
Though connection is establishing but when I try to access any model in service file using require. It breaks with this error message. Where I am doing wrong.
I think you need to use the instance of sequelize, not the class. So sequelize.define not Sequelize.define.
Also, you need to instantiate it properly: var sequelize = new Sequelize(...)