Cannot read properties of undefined (reading 'findOne') (in sequelize model) - node.js

I tried logging in via postman. but it has been discontinued.
like that
I used the console log for the corresponding problem line, and the model user was undefined. But I've connected it properly and I'm not sure why it's an error.
my code is like that
index.js
const { user } = require("../../entities/models/user");
console.log('login 2:',user)
const userInfo = await user.findOne({
where: { email: req.body.email, social: 'google'}
})
models/user.js
'use strict';
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 associate(models) {
// define association here
}
};
user.init({
username: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING,
social: DataTypes.STRING,
socialid: DataTypes.STRING,
gender: DataTypes.STRING,
age: DataTypes.INTEGER,
height: DataTypes.STRING,
weigt: DataTypes.STRING,
profileimage: DataTypes.STRING,
total_time: DataTypes.INTEGER
}, {
sequelize,
modelName: 'user',
});
return user;
};
I don't understand. Obviously, when I click the path require("../../entities/models/user"); , it works well with the model, but why does undefined keep popping up?

You are exporting whole module from models/user.js so you need to import it like this:
const user = require("../../entities/models/user");
Also, you need to call user with (sequelize, DataTypes), so:
const Sequelize = require('sequelize');
const sequelize = new Sequelize(/*your config here*/)
const user = require("../../entities/models/user")(sequelize, Sequelize);

Related

Postman GET request return "null" with Sequelize DB

Currently, I am working on a CRUD project with React and Sequelize.
I have a page with a search bar to look for users.
My front and back were working fine, but since I modified my User and Post models just by adding a foreignkey (id), nothing works and when I test with Postman, the request passes, but it returns "null".
I can't figure out what the problem is and why I get a "null" whereas my DB contains users.
User model:
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
models.User.hasMany(models.Post, {
foreignKey: 'id'
});
models.User.hasMany(models.Comment);
}
};
User.init({
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING,
imageUrl: DataTypes.STRING,
isAdmin: DataTypes.BOOLEAN
}, {
sequelize,
modelName: 'User',
});
return User;
};
Controller to get all Users:
User.findAll({
order: [
['id', 'DESC']
]
})
.then((users) => {
let result = []
for (i in users) {
let firstName = users[i].firstName;
let lastName = users[i].lastName;
let email = users[i].email;
let imageUrl = users[i].imageUrl;
result.push({
firstName,
lastName,
email,
imageUrl
})
}
res.status(200).json(result)
})
.catch((err) => res.status(500).send({
err
}))}
I tried several ways for the controller (a simple "const users = await User.findAll();
res.status(200).json(users)", instead of the i put 0 to browse users, etc ), I always get a "null" result.
Could someone please help me?

Node JS Sequelize many-to-many relationship throwing error column id does not exist

I am building a Node JS web application. I am using Sequelize, https://sequelize.org/ for manipulating the database logic. Now, I am having a problem with bulk insert and many-to-many relationships.
I have a model called, Region with the following code.
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Region extends Model {
static associate(models) {
// define association here
Region.belongsToMany(models.ExchangeRequest, {
through: 'RegionExchangeRequests',
as: 'exchangeRequests',
foreignKey: "region_id",
otherKey: "exchange_request_id"
})
}
};
Region.init({
name: DataTypes.STRING,
latitude: DataTypes.FLOAT,
longitude: DataTypes.FLOAT
}, {
sequelize,
modelName: 'Region',
});
return Region;
};
Then, I have a model called, ExchangeRequest with the following code.
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class ExchangeRequest extends Model {
static associate(models) {
// define association here
ExchangeRequest.belongsToMany(models.Region, {
through: 'RegionExchangeRequests',
as: 'regions',
foreignKey: 'exchange_request_id',
otherKey: "region_id"
})
ExchangeRequest.belongsTo(models.User, { foreignKey: 'userId', as: 'user', onDelete: 'cascade' });
}
};
ExchangeRequest.init({
exchange_rate: DataTypes.DECIMAL,
currency: DataTypes.STRING,
amount: DataTypes.DECIMAL,
buy_or_sell: DataTypes.INTEGER,
note: DataTypes.STRING,
email: DataTypes.STRING,
phone: DataTypes.STRING,
address: DataTypes.STRING,
userId: DataTypes.INTEGER
}, {
sequelize,
modelName: 'ExchangeRequest',
});
return ExchangeRequest;
};
Then I have the RegionExchangeRequest with the following code.
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class RegionExchangeRequest extends Model {
static associate(models) {
// define association here
}
};
RegionExchangeRequest.init({
region_id: DataTypes.INTEGER,
exchange_request_id: DataTypes.INTEGER
}, {
sequelize,
modelName: 'RegionExchangeRequest',
});
return RegionExchangeRequest;
};
I have a function that is doing the bulk insert on RegionExchangeReques as follow.
const create = async ({
exchange_rate,
currency,
amount,
buy_or_sell,
note,
email,
phone,
address,
region_ids,
userId
}) => {
try {
let exchangeRequest = await ExchangeRequest.create({
exchange_rate,
currency,
amount,
buy_or_sell,
note,
email,
phone,
address,
userId
});
if (region_ids && region_ids.length > 0) {
let pivotData = [ ];
region_ids.forEach(regionId => {
pivotData.push({
exchange_request_id: exchangeRequest.id,
region_id: regionId
})
})
let regionExchangeRequests = await RegionExchangeRequest.bulkCreate(pivotData);
}
return {
error: false,
data: exchangeRequest
}
} catch (e) {
return {
error: true,
code: 500,
message: e.message
}
}
}
When the function is called, it is throwing the following error.
"column \"id\" of relation \"RegionExchangeRequests\" does not exist"
The following line is throwing the error.
let regionExchangeRequests = await RegionExchangeRequest.bulkCreate(pivotData);
What is wrong with my code and how can I fix it?
In many-to-many relationship you specified RegionExchangeRequests as through table that connects two other tables, and in sequelize you cannot call usual model methods in through table.To do so you need to create super many-to-many relationship, for more information check out this link advanced-associations-in-sequelize

Getting sequelize attribute notNull violation in my create controller due to variable name being different from column name

Im trying to add users into my database using bcrypt so I can has their passwords, but when I set the req.body to the bcrypt variable I get a notNull Violation: Users.user_password cannot be null.
This is my model I used to define my users table
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Users 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
}
};
Users.init({
user_id:{
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
user_name:{
type: DataTypes.STRING,
allowNull: false
},
user_email:{
type: DataTypes.STRING,
allowNull: false
},
user_password:{
type: DataTypes.STRING,
allowNull: false
},
}, {
sequelize,
timestamps: false,
modelName: 'Users',
tableName: 'users'
});
return Users;
};
This is the controller I'm using to add a new user. At the bottom when I pass in the bcryptPassword variable instead of the user_password thats deconstructed at the top, I get the notNull Violation. But if I dont pass in the bcryptPassword variable I can create a new user. Does anyone know why this is happening? Is there a way to config the model so I can use any vairable? Any help would be greatly appreciated!
Thanks!
const { Users } = require('../models');
const bcrypt = require('bcrypt');
module.exports = {
createUser: async(req, res) => {
const { user_name, user_email, user_password } = req.body;
try {
const salt = await bcrypt.genSalt(10);
const bcryptPassword = await bcrypt.hash(user_password, salt)
const newUser = await Users.create({ user_name, user_email, bcryptPassword });
return res.json(newUser);
} catch (error) {
console.error(error.message);
return res.status(500).json(error);
}
}
}
I found a viable answer while searching through the sequelize documentation.
https://sequelize.org/master/manual/getters-setters-virtuals.html
I used the set() function in my user_password field and that worked. Every time I created a new user the password was hashed in the database using bcrypt.
Here is the modified model code. Changes are marked by asterics.
'use strict';
*****const bcrypt = require('bcrypt');*****
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Users 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
}
};
Users.init({
user_id:{
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
user_name:{
type: DataTypes.STRING,
allowNull: false
},
user_email:{
type: DataTypes.STRING,
allowNull: false
},
user_password:{
type: DataTypes.STRING,
allowNull: false,
*****set(value) {
const hash = bcrypt.hashSync(value, 10);
this.setDataValue('user_password', hash);
}*****
},
}, {
sequelize,
timestamps: false,
modelName: 'Users',
tableName: 'users',
});
return Users;
};

sequlize model cannot be fetched

I am using this scotch tutorial to create a basic node application using the sequelize js for ORM, here is my models/index.js:
and I am unable to use my user model with the user controller:
my model :
'use strict';
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define('user', {
name: {
type : DataTypes.STRING,
allowNull : false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
}
}, {});
user.associate = function(models) {
user.hasMany(models.wish, {
foreignKey: 'user_id',
as: 'wishes'
});
};
return user;
};
and here is my controller:
const user = require('../models').user;
module.exports = {
create(req, res){
return user.create({
name: req.body.name,
email: req.body.email,
password: req.body.password }).then(
todo => res.status(201).send(user)
).catch(
error => res.status(400).send(error)
);
}
}
but for some reason a big error comes on my screen and crashes the application, what I diagnosed from that error is that my controller is not able to find the 'user' model AND and I tried to link a bunch of things like giving the path to user directly but it did not work.
here is the error if you need (I am a newbee so could be totaly wrong about this)
I think you should change this line :
const user = require('../models').user;
to
const user = require('../models');

Sequelize - called with something that's not a subclass of Sequelize.Model

I'm working on app but I having this issue using Node.js and Sequelize for Postgresql :
throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not a subclass of Sequelize.Model');
^
Error: Expense.class BelongsTo extends Association {
constructor(source, target, options) {
super(source, target, options);
<....LOT OF CODE FROM SEQUELIZE ....>
if ((fieldsOrOptions || {}).transaction instanceof Transaction) {
options.transaction = fieldsOrOptions.transaction;
}
options.logging = (fieldsOrOptions || {}).logging;
return association.target.create(values, fieldsOrOptions).then(newAssociatedObject =>
sourceInstance[association.accessors.set](newAssociatedObject, options)
);
}
} called with something that's not a subclass of Sequelize.Model
I don't understand this error, especially the last line "called with something that's not a subclass of Sequelize.Model".
Here is the models :
User model
const models = require('./index');
const Expense = models.User;
module.exports = (sequelize, DataTypes) => {
var User = sequelize.define('User', {
firstname: DataTypes.STRING,
lastname: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.Expense);
}
}
});
console.log(models);
User.hasMany(Expense, {as: 'Expenses', foreignKey: 'userId'});
return User;
};
And Expense model
const models = require('./index');
const User = models.User;
module.exports = (sequelize, DataTypes) => {
var Expense = sequelize.define('Expense', {
name: DataTypes.STRING,
amount: DataTypes.INTEGER,
date: DataTypes.INTEGER
}, {
classMethods: {
}
});
Expense.belongsTo(User, { foreignKey: 'userId' });
return Expense;
};
And the controller for creating an expense :
createExpense: function(req, res) {
const user = User.findOne({ where: { id: req.params.id } });
Expense.create({
name: req.body.name,
amount: req.body.amount,
date: req.body.date,
User: user
},{
include: [
{
model: User
}
]
}).then((created) => {
res.status(200).send({ success: true, message: 'Dépense ajoutée !' });
});
}
Does someone have already see an error that look like that ? I search for few days without any issue, if someone could help I'll really appreciate,
thank !
I have a same problem before, but I found a reason. Key point is that your models must under a same sequelize class.
You can look my project mini-shop on github.
Though being 3 years late... I think, it's caused by a bad import. The import in in "User Model" for the "Expense Model" uses this line and looks kind of fishy:
const Expense = models.User;
But from a rather general point of view, this kind of error message might be a hint to an error while creating an association in a line such as User.hasMany(Expense, {as: 'Expenses', foreignKey: 'userId'});
Here is another answer regarding a similar question. For example in my case, the error came from not using the definition name to access my model (<- depends on your setup!)

Resources