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,
}],
})
Related
I am creating a mongoose model called User. Then when I import the model on the two different controllers the mongoose show me the error 'OverwriteModelError: Cannot overwrite User model once compiled. at Mongoose.model'
Please help me if there is any one who face this error before.
My User Model
User.js
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
min: 2,
max: 100,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 5,
},
city: String,
state: String,
country: String,
occupation: String,
phoneNumber: String,
transactions: Array,
role: {
type: String,
enum: ["user", "admin", "superadmin"],
default: "admin",
},
},
{ timestamps: true }
);
const User = mongoose.model('User', UserSchema) ;
export default User;
`
The controllers
Client.js
`
import User from "../models/User.js";
export const getCustomers = async (req, res) => {
try {
const customers = await User.find({ role: "user" }).select("-password");
res.status(200).json(customers);
} catch (error) {
res.status(404).json({ message: error.message });
}
};
`
General.js
`
import User from '../models/user.js'
export const getUser = async (req, res) => {
try {
const { id } = req.params;
const user = await User.findById(id);
res.status(200).json(user);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
`
Try to check if the model is already declared before exporting it:
const User = mongoose.models.User || mongoose.model('User', UserSchema);
export default User;
I am getting TypeError: Cannot read properties of undefined (reading 'findAll') error and I couldn't find why. Here is my index.js and User.js files in models folder;
index.js;
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const config = require('../../config/database.js');
const db = {};
const sequelize = new Sequelize(config);
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.hostname] = model;
db[model.username] = model;
db[model.password] = model;
db[model.command] = model;
db[model.status] = model;
db[model.cpu] = model;
db[model.mac] = model;
db[model.info] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
User.js;
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
/* id : DataTypes.INTEGER, */
hostname: DataTypes.STRING,
username: DataTypes.STRING,
password: DataTypes.STRING,
command: DataTypes.STRING,
status: DataTypes.STRING,
cpu: DataTypes.INTEGER,
mac: DataTypes.STRING,
info: DataTypes.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
};
return User;
};
And here is my controller UserController.js file ;
const { User } = require('../models');
module.exports = {
index(req, res) {
User.findAll({})
.then(users => res.json({
error: false,
data: users
}))
.catch(error => res.json({
error:true,
data: [],
error: error
}));
},
create(req, res) {
const { /* id, */hostname,username,password,command,status,cpu,mac,info} = req.body;
User.create({
/* id, */hostname,username,password,command,status,cpu,mac,info
})
.then(user => res.status(201).json({
error: false,
data: user,
message: "new user has been created"
}))
.catch(error => res.json({
error:true,
data: [],
error: error
}));
},
update(req, res) {
const user_id = req.params.id;
const { hostname,username,password,command,status,cpu,mac,info } = req.body;
User.update({
hostname,username,password,command,status,cpu,mac,info
}, {
where: {
id: user_id
}
})
.then(user => res.status(201).json({
error: false,
data: user,
message: 'user has been updated'
}))
.catch(error => res.json({
error: true,
error: error
}));
},
destroy(req, res) {
const user_id = req.params.id;
User.destroy({ where: {
id: user_id
}})
.then(status => res.status(201).json({
error: false,
message: 'user has been deleted'
}))
.catch(error => res.json({
error: true,
error: error
}));
}
}
I couldn't figure out what caused this problem. I'd be glad if you could help.Here is my project directory ;
directory
You're passing an empty object to User.findAll({}) in your UserController.js file.
Try User.findAll(), instead.
I had the same problem just last night, and it was happening to me because I was calling findAll() before I synced sequelize sequelize.sync(). That is why it is returning undefined. Not sure if it happening to you for the same reason because you haven't attached the code for your server.js. Also either pass in an attribute prop inside the findAll({}) or get rid of the curly braces.
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).
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()...
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)