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');
Related
I am a nodeJs developer, I failed to get the list of users, when I tested my code on postman it gives me the error below:
User.find is not a function
The following is my user.js file
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
}
}
User.init({
username: {
type:DataTypes.STRING,
allowNull: false,
},
email: {
type:DataTypes.STRING,
allowNull: false,
},
password: {
type:DataTypes.STRING,
allowNull: false,
},
role: {
type:DataTypes.STRING,
allowNull: false,
},
}, {
sequelize,
tableName:'users',
modelName: 'User',
});
return User;
};
and this is where it's imported/required
const router = require('express').Router();
let User = require('../models/user');
router.route('/getUser').post((req, res) => {
User.find({})
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ', err));
});
The user.js file that you provided is exporting a function that create the User class (and not actually the User model class)
Did you already init this class elsewhere and you are importing the wrong file ?
It didn't work, I did as you told me but it gives me back:
sequelize id not defined
Also I don't think that the problem is in the model because I have used it before and in the login I used .find and it worked without any problem!
this login code :
router.post('/login', async (req,res,next) => {
const user = await User.findOne({ where: { email: req.body.email }});
if (user) {
const password_valid = await bcrypt.compare(req.body.password,user.password);
if (password_valid) {
token = JWT.sign({
isLogin: true,
"id": user.id,
"email": user.email,
"username": user.username
},"12345678");
res.status(200).json({token :token});
} else {
res.status(400).json({isLogin : false, error: "password incorrect" });
}
} else {
res.status(404).json({isLogin : false, error :"User does not exist"});
}
});
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?
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);
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!)
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.