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).
Related
I am new to node js environment and currently I am practicing a crud applicaiton
I am using sequelize as ORM and I have used the mvc structure
npm install --save sequelize
$ npm install --save pg pg-hstore
I am using sequelize cli
npm install --save-dev sequelize-cli
npx sequelize-cli init
It is my migration
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Books', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Books');
}
};
My Model:
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Books 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 associate(models) {
// define association here
}
};
Books.init({
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING
}, {
sequelize,
modelName: 'Books',
});
return Books;
};
MY Controller:
exports.allBooks = (req,res)=>{
const bookme = Books(**how to pass sequelize**,**how to pass sequelize datatype**)
var booksJSON = bookme.findAll()
res.json(booksJSON)
console.log(JSON.stringify(booksJSON))
}
I am getting the empty response if I pass the datatypes customly by creating a connection manually to database with sequelize and passing that sequelize to the books models
I think that my mistake is in passing these parameters. What and how shoudld I pass to the Books model
I am importing the books model as follows in my controller:
const Books = require('../models/books.js');
also when i ran the bootstraping that created migrations,models,seeding folders it also created a index.js file in models folder
I have tried passing that too in the parameter to Books model but It gave error
index.js in models folder created by sequelize cli package itself
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/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);
}
fs
.readdirSync(__dirname)
.filter(file => {
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;
The error I got when I try to pass this db from index.js to Books model in my controller is:
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
^
TypeError: Class constructor model cannot be invoked without 'new'
What should I pass to the parameter and from where?
I am getting response by using aysnc and await. I used second parameter by importing directly from the package
const Sequelize = require('sequelize')
and for first parameter I used the manually created connection.
but it still doesn't clears my concern of actually what parameters were to pass
I am using Express.js with sequelize
I am trying to get data from table but findALL() method not working
Here , I am sharing my models & controller file
checkout_product model
module.exports = function (sequelize, DataTypes) {
var Checkout_product = sequelize.define(
"Checkout_products",
{
name: {
type: DataTypes.STRING
},
ptice: {
type: DataTypes.STRING
},
image: {
type: DataTypes.STRING
},
quantity: {
type: DataTypes.INTEGER
},
},
);
Checkout_product.associate = function (models) {
Checkout_product.hasMany(models.Product_attribute, {
foreignKey: "product_id",
sourceKey: "id"
});
};
return Checkout_product;
};
product_attribute model
module.exports = function (sequelize, DataTypes) {
var Product_attribute = sequelize.define(
"product_attributes",
{
product_id: {
type: DataTypes.INTEGER
},
attribute_name: {
type: DataTypes.STRING
},
attribute: {
type: DataTypes.STRING
},
price: {
type: DataTypes.STRING
},
},
);
Product_attribute.associate = (models) => {
Product_attribute.belongsTo(models.Checkout_product, {
foreignKey: "product_id",
sourceKey: "id"
});
};
return Product_attribute;
};
models/index.js file
"use strict";
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const config = require("./../config/development").database;
let sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
let db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return file.indexOf(".") !== 0 && file !== "index.js";
})
.forEach(function(file) {
let model = require(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
Controller
const Checkout_product = require('../models');
module.exports.checkout_product_get = function (req, res) {
Checkout_product.findAll({
include: [ {
model : Product_attributes,
}]
})
.then(checkout_product => {
res.json(checkout_product)
})
}
I am stuck to get data from checkout_product & it's child model product_attribute model,
Everytime I am getting same error : TypeError: Checkout_product.findAll is not a function
const Checkout_product = require('../models').table_name;
Can you try it
You are using the deprecated - legacy way of Sequelize to initialize models. Newer ways with require and extends are available and suggested. Check the docs for more information.
Regarding your code....
You are neither initializing the db structure properly nor using it correctly later...
First your code here in index.js:
.forEach(function(file) {
let model = require(path.join(__dirname, file));
db[model.name] = model;
});
Just loads the model files in the db object. But these files are functions ment to be called with sequelize object as parameter. This is done by providing them to sequelize.import that manages the proper call of the defined model-functions to create the model instances. Check https://sequelize.org/master/manual/models-definition.html
Also after successfully initializing the db, in your controller code, the require('../models') returns the total db object. So if you want to use a specific model as Checkout_product in your case, you have to access it in the object:
const db = require('../models');
db.Checkout_product.findAll()...
Here are my models : sensor.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Sensor = sequelize.define('Sensor', {
sensorName: DataTypes.STRING,
user: DataTypes.INTEGER
}, {});
Sensor.associate = function(models) {
Sensor.hasMany(models.User, {
foreignKey: 'user'
})
};
return Sensor;
};
user.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING
}, {});
User.associate = function(models) {
User.belongsTo(models.Sensor, {
foreignKey: 'user'
})
};
return User;
};
While doing
Sensor.findAll({
'raw':true,
include: [{
model: User
}]
})
.then(function(result){
console.log(result)
})
I'm getting the following error :
Unhandled rejection SequelizeEagerLoadingError: User is not associated to Sensor!
You are creating a column (user) with the same name as the object relationship which is likely causing a conflict. By default Sequelize will create the userId (or user_id depending on settings) column automatically and you don't need to include it in the define() or the association, whereas you are using user for the ID an relationship.
Use the as property to define 1:n relationships as they are pluralized.
sensor.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Sensor = sequelize.define('Sensor', {
sensorName: DataTypes.STRING,
}, {});
Sensor.associate = function(models) {
Sensor.hasMany(models.User, { as: 'users' })
};
return Sensor;
};
user.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING
}, {});
User.associate = function(models) {
User.belongsTo(models.Sensor)
};
return User;
};
query
Sensor.findAll({
include: [{
model: User,
as: '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
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)