Currently, I am using sequelize v6.2.0 with node.js for creating rest apis.
I want to add profile
data to user
by using scopes
like below.
Unfortunately, it's making include.model.getTableName is not function
error.
(models/user.js)
'use strict';
const {
Model,
} = require('sequelize');
const Profile = require('./profile');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
// define association here
User.hasOne(models.Profile, {
foreignKey: 'userId',
as: 'profile',
});
}
};
User.init({
username: {
type: DataTypes.STRING,
allowNull: true,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: true,
},
isVerified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
isAdmin: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
isDeleted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
token: {
type: DataTypes.STRING,
allowNull: false,
},
}, {
scopes: {
withProfile: () => ({
include: [
{
as: 'profile',
model: Profile,
},
],
}),
},
sequelize,
modelName: 'User',
});
return User;
};
(models/profile.js)
'use strict';
const {
Model,
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Profile extends Model {
static associate(models) {
Profile.belongsTo(models.User, {
foreignKey: 'userId',
as: 'user',
});
}
};
Profile.init({
userId: {
type: DataTypes.INTEGER,
allowNull: false,
},
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
birthday: {
type: DataTypes.DATE,
allowNull: true,
},
location: {
type: DataTypes.STRING,
allowNull: true,
},
gender: {
type: DataTypes.STRING,
allowNull: false,
},
phone: {
type: DataTypes.STRING,
allowNull: true,
},
}, {
sequelize,
modelName: 'Profile',
});
return Profile;
};
(controllers/auth.controller.js)
const me = (req, res) => {
const scopes = ['withProfile'];
try {
// This is making error....
models.User.scope(scopes).findOne({
where: {
id: req.user.id,
},
attributes: {
exclude: ['password', 'token'],
},
}).then((result) => {
return res.status(200).json({
data: result.dataValues,
});
}).catch((error) => {
return res.status(500).json({
message: error.message,
});
});
} catch (error) {
return res.status(500).json({
message: error.message,
});
}
};
How can I fix this issue?