Sequelize.define is not a function - javascript

I've recently started to play around with node.js so i am new to this. I'm getting the following error in my node.js console Can't upload images yet apparently because of my rating, please click the link
Below is my code.
var Sequelize = require('sequelize');
const dbConfig = new Sequelize('Mike_Test', 'sa', '[DBPASSWORD]', {
host:'179.27.69.555',
dialect: 'mssql',
port: 1433,
pool: {
max: 5,
min: 0,
idle: 10000
},
});
//Model Schhema
function createDB(){
var Customer2 = Sequelize.define('Customers2', {
Name: {
Name: Sequelize.STRING,
allowNull: false
},
Email: {
Email: Sequelize.STRING,
allowNull: false
},
Phone: {
Phone: Sequelize.STRING,
allowNull: false
},
Webiste: {
Webiste: Sequelize.STRING,
allowNull: true
},
Message: {
Message: Sequelize.STRING,
allowNull: true
},
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
})
//Creates DB if it does not exist already.
Customer2.sync({force:true}).then(function() {
//Add to Cstomers2 Table
Customer2.create({Name: "Michael Sony", Email:
"michael#locationextreme.com", Phone: "01865657000", Website:
"https://www.youtbe.com", Message: "Blah Blah Blah!"})
});
};
createDB();
I have connected to a DB [Customers] with the above connection details successfully, but I can't create a new database and write to it [Customers2]
Changed code
var Sequelize = require('sequelize');
const dbConfig = new Sequelize('Mike_Test', 'sa', 'Georged0g', {
host:'172.27.60.139',
dialect: 'mssql',
port: 1433,
pool: {
max: 5,
min: 0,
idle: 10000
},
});
//Model Schhema
function createDB(){
var Customer2 = dbConfig.define('Customers2', {
Name: {
Name: Sequelize.STRING,
allowNull: false
},
Email: {
Email: Sequelize.STRING,
allowNull: false
},
Phone: {
Phone: Sequelize.STRING,
allowNull: false
},
Webiste: {
Webiste: Sequelize.STRING,
allowNull: true
},
Message: {
Message: Sequelize.STRING,
allowNull: true
},
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
})
//Creates DB if it does not exist already.
Customer2.sync({force:true}).then(function() {
//Add to Cstomers2 Table
Customer2.create({Name: "Michael Sony", Email:
"michael#locationextreme.com", Phone: "01865657000", Website:
"https://www.youtbe.com", Message: "Blah Blah Blah!"})
});
};
createDB();

Related

How create (optimize) service on Backend (ExpressJS) with sequelize

Tried to create API for internet store using ExpressJS and sequelize. I have users, basket and devices. To connect basket and choosen by user devices used middle table BasketDevice.
Models:
export const Models = {
User: sequelize.define('user',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
email: { type: DataTypes.STRING, unique: true },
password: { type: DataTypes.STRING },
role: { type: DataTypes.STRING, defaultValue: 'USER' },
isActivated: { type: DataTypes.BOOLEAN, defaultValue: false},
activationLink: { type: DataTypes.STRING, unique: true }
}
),
Basket: sequelize.define('basket',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
}
),
BasketDevice: sequelize.define('basketDevice',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
}
),
Device: sequelize.define('device',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING, allowNull: false, unique: true },
price: { type: DataTypes.INTEGER, allowNull: false },
img: { type: DataTypes.STRING, allowNull: false },
rating: { type: DataTypes.INTEGER, defaultValue: 0 },
}
}
Assotiations between tables:
Models.User.hasOne(Models.Basket)
Models.Basket.belongsTo(Models.User)
Models.Basket.hasMany(Models.BasketDevice, {as: 'devices'})
Models.BasketDevice.belongsTo(Models.Basket)
Models.Device.hasMany(Models.BasketDevice)
Models.BasketDevice.belongsTo(Models.Device)
Tryed to give in response basket include basket device
Basket service:
class BasketService {
async getBasket(token: string) {
const userData = await TokenService.verifyRefreshToken(token) as any
const basket = await Models.Basket.findOne({
where: { userId: userData.id },
include: [{model: Models.BasketDevice, as: 'devices'}]
})
return basket
}
}
Don't know how create getBasket function that gives added to cart devices and counting of one device
What is the opltimal way to give devices added in basket?

Create a model with hash password in Sequelize?

I'm trying to create a model in Sequelize with a hash password using bcrypt, and run "sequelize db:migrate" but I can't. I get this error whenever I try to run it. All I need to is have "password" with the hash already done. I don't know where I'm going wrong or what I'm missing. can anybody help me?
== 001-user: migrating =======
ERROR: s.replace is not a function
I'm using: Sequelize: 6.16.2. Database: Postgres. Node: 15. Bcrypt: 5.0.1
Here is my User model:
class User extends Model {
/**
* #param {import("../index")} models
*/
static associate (models) {
User.belongsTo(models.UserRole, { as: "user_role", foreignKey: "id_user_role" });
}
}
/**
* #param {import("sequelize").Sequelize} sequelize Connection with the database
*/
function initUser (sequelize) {
User.init({
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
user: DataTypes.STRING(30),
name: DataTypes.STRING(100),
email: DataTypes.STRING(100),
password: DataTypes.STRING(100),
id_user_role: {
type: DataTypes.INTEGER,
references: {
model: sequelize.models.UserRole,
key: "id"
}
},
deleted: DataTypes.BOOLEAN
},
{
sequelize,
timestamps: false,
modelName: "User",
tableName: "user",
underscored: true,
hooks: {
beforeCreate: async (user) => {
if (user.password) {
const salt = await bcrypt.genSaltSync(11, "a");
user.password = bcrypt.hashSync(user.password, salt);
}
},
beforeUpdate: async (user) => {
if (user.password) {
const salt = await bcrypt.genSaltSync(11, "a");
user.password = bcrypt.hashSync(user.password, salt);
}
}
}
});
return User;
}
module.exports = { initUser };
User migration:
module.exports = {
/**
* #param {import("sequelize").QueryInterface} queryInterface
* #param {import("sequelize").DataTypes} Sequelize
*/
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable("user", {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
user: {
type: Sequelize.STRING(30),
allowNull: false
},
name: {
type: Sequelize.STRING(100),
allowNull: false
},
email: {
type: Sequelize.STRING(100),
allowNull: false
},
password: {
type: Sequelize.STRING(100),
allowNull: false
},
id_user_role: {
type: Sequelize.INTEGER,
allowNull: false,
references: { model: UserRole, key: "id" }
},
deleted: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
}
});
await queryInterface.bulkInsert("user", [
{
user: "admin", name: "test", email: "test#admin.com", password: "admin", id_user_role: 1
},
{
user: "comum", name: "test", email: "test#comum.com", password: "comum", id_user_role: 2
},
{
user: "regular", name: "test", email: "test#regular.com", password: "comum", id_user_role: 3
}
]);
}
};

Inserting data in multiple tables using Sequelize

It's my first time using Sequelize with MySQL and would like to understand how to insert data into two tables with a foreign key dependency.
Let's say, I have two tables - bookingDescription and bookingSummary. The entities for the same are as follows
//bookingSummary
module.exports = (sequelize, DataTypes) => {
return sequelize.define('bookingSummary', {
headerId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true,},
titleId: DataTypes.STRING,
abNumber: DataTypes.INTEGER,
userProfileId: DataTypes.INTEGER,
theatreId: DataTypes.STRING,
mFId: DataTypes.STRING,
createdBy: { type: DataTypes.TEXT, allowNull: false },
modifiedBy: { type: DataTypes.TEXT, allowNull: false },
status: DataTypes.STRING
}, {
tableName: 'booking_summary',
underscored: true
})
}
//bookingDescription
module.exports = (sequelize, DataTypes) => {
return sequelize.define('bookingWeek', {
lineId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true,},
headerId: DataTypes.STRING,
titleId: DataTypes.STRING,
abNumber: DataTypes.INTEGER,
theatreId: DataTypes.STRING,
mFId: DataTypes.STRING,
theatreName: DataTypes.STRING,
city: DataTypes.STRING,
state: DataTypes.STRING,
playStartDate: DataTypes.DATE,
playEndDate: DataTypes.DATE,
preferredFormat: DataTypes.INTEGER,
screensInDay: DataTypes.INTEGER,
featureTypeFlag: DataTypes.TEXT,
cofeatureName: DataTypes.STRING,
exhbtrReqComment: DataTypes.STRING,
createdBy: { type: DataTypes.TEXT, allowNull: false },
modifiedBy: { type: DataTypes.TEXT, allowNull: false },
status: DataTypes.STRING
}, {
tableName: 'booking_description',
underscored: true
})
}
Foreign key references in bookingSummary are as follows
FOREIGN KEY (headerId) REFERENCES bookingSummary(headerId)
FOREIGN KEY (titleId, abNumber, mFId)
REFERENCES bookingSummary(abNumber)
I have an object of data which needs to be inserted into the tables at an instant.
Any idea on how to approach this ?
So, i would recommend you first learning about SQL relations, regardless of Sequelize, and your current project structure, because it seems to me that you still lack the basic understanding of the logic behind these associations, where they should be used and how.
Both your tables have duplicate fields, which makes no sense. Take a look here, for example: https://code.tutsplus.com/articles/sql-for-beginners-part-3-database-relationships--net-8561
As for your current code, i played with it a bit, and this is what i did(will work only if you're using model.sync(), because a column needs to be created automatically. Also use force:true if you already have the tables):
module.exports = (sequelize, DataTypes) => {
const bookingHeader = sequelize.define('bookingHeader', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
abNumber: DataTypes.INTEGER,
userProfileId: DataTypes.INTEGER,
theatreId: DataTypes.STRING,
mFId: DataTypes.STRING,
createdBy: { type: DataTypes.TEXT, allowNull: true },
modifiedBy: { type: DataTypes.TEXT, allowNull: true },
status: DataTypes.STRING
}, {
tableName: 'booking_header',
// underscored: true
})
bookingHeader.associate = function (models) {
bookingHeader.hasOne(models.bookingDescription);
};
return bookingHeader;
}
Booking description:
module.exports = (sequelize, DataTypes) => {
const bookingDescription = sequelize.define('bookingDescription', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, },
abNumber: DataTypes.INTEGER,
theatreId: DataTypes.STRING,
mFId: DataTypes.STRING,
theatreName: DataTypes.STRING,
city: DataTypes.STRING,
state: DataTypes.STRING,
playStartDate: DataTypes.DATE,
playEndDate: DataTypes.DATE,
preferredFormat: DataTypes.INTEGER,
screensInDay: DataTypes.INTEGER,
featureTypeFlag: DataTypes.TEXT,
cofeatureName: DataTypes.STRING,
exhbtrReqComment: DataTypes.STRING,
createdBy: { type: DataTypes.TEXT, allowNull: false },
modifiedBy: { type: DataTypes.TEXT, allowNull: false },
status: DataTypes.STRING
}, {
tableName: 'booking_description',
// underscored: true
})
bookingDescription.associate = function (models) {
bookingDescription.belongsTo(models.bookingHeader);
};
return bookingDescription;
}
In your route, you can do something like this:
const {bookingHeader,bookingDescription} = models;
app.post("/booking", async (req, res, next) => {
try {
const header = await bookingHeader.create(req.body)
const headerId = header.id
await bookingDescription.create({state:'active',createdBy:'somebody',modifiedBy:'somebody',bookingHeaderId:headerId})
res.json(header);
} catch (error) {
console.log(error)
res.status(500)
}
});
Notice that i hardcoded some of the fields for the description, just for example purposes. Also, it's possible that there is a "better" way to do this with Sequelize, but the docs are really poor, so this gets the job done.

Sequelize Seeding ARRAY(ENUM)

I cannot seem to figure out how to seed ARRAY(ENUM) using Sequelize. When I am registering a user via my app, I can create a new user fine, but when I am using the queryInterface.bulkInsert in a seed file, I am getting:
ERROR: column "roles" is of type "enum_Users_roles"[] but expression is of type text[]
here is my code:
return queryInterface.bulkInsert('Users', [
{
email: faker.internet.email(),
roles: ['user'],
password: "hash",
public_id: faker.random.uuid(),
created_at: new Date(),
updated_at: new Date()
}
]);
and here is my migration file for the user:
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
email: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
},
roles: {
type: Sequelize.ARRAY(Sequelize.ENUM({
values: ['user', 'setter', 'admin']
})),
allowNull: false
},
public_id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
created_at: {
allowNull: false,
type: Sequelize.DATE
},
updated_at: {
allowNull: false,
type: Sequelize.DATE
}
})
I am just assuming that I am doing it wrong, but I cannot find any documentation on how to do it correctly. If anyone can help and explain (teach a man to fish), I would appreciate it.
Someone answered on github here
This is their answer which worked for me (and I greatly appreciate)
You can use this code
class Item extends Sequelize.Model { }
Item.init({
name: { type: DataTypes.STRING },
values: {
type: DataTypes.ARRAY(DataTypes.ENUM({
values: ['a', 'b']
}))
}
}, {
sequelize,
timestamps: true
})
sequelize.sync({ force: true }).then(async () => {
await sequelize.queryInterface.bulkInsert('Items', [
{
name: 'xyz',
values: sequelize.literal(`ARRAY['a']::"enum_Items_values"[]`),
createdAt: new Date(),
updatedAt: new Date()
}
]);
});
Executing (default): INSERT INTO "Items" ("name","values","createdAt","updatedAt") VAL
[1]: https://github.com/sequelize/sequelize/issues/11541#issuecomment-542791562
Obviously you'll want to change the array values and enum values. For example, mine would be
ARRAY['user']::"enum_Users_values"[]

Sequelize request error SequelizeEagerLoadingError

I’m new with sequelize I’m trying to make a request with associate tables
I have a first model called Experience
module.exports = function (sequelize, DataTypes) {
const Experience = sequelize.define('experience', {
internalId: {
type: DataTypes.BIGINT,
unique: true,
allowNull: false,
},
label: {
type: DataTypes.STRING,
unique: false,
allowNull: false,
},
picture: {
type: DataTypes.TEXT,
unique: false,
allowNull: true,
},
type: {
type: DataTypes.STRING,
validate: {
isIn: {
args: [[
'generic',
'specific',
]],
msg: 'Must be a valid type',
},
},
unique: false,
allowNull: true,
},
author: {
type: DataTypes.STRING,
unique: false,
allowNull: true,
defaultValue: 'import',
},
isActive: {
type: DataTypes.BOOLEAN,
defaultValue: true,
},
});
Experience.associate = (models) => {
Experience.belongsToMany(models.Tag, {
as: 'Tags',
through: models.ExperienceTag,
});
};
return Experience;
};
a second called Tags
module.exports = function (sequelize, DataTypes) {
const Tag = sequelize.define('tag', {
internalId: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
unique: false,
allowNull: false,
},
author: {
type: DataTypes.STRING,
unique: false,
allowNull: true,
defaultValue: 'import',
},
isActive: {
type: DataTypes.BOOLEAN,
defaultValue: true,
},
});
Tag.associate = (models) => {
Tag.belongsToMany(models.Experience, {
as: 'Experiences',
through: models.ExperienceTag,
});
};
return Tag;
};
The association table name was ExperienceTags
I would like get all the Experiencewho have a tagId = 44
This is my request:
Experience.findAll({
include: [{
model: ExperienceTag,
where: { tagId: 44 },
}],
})
.then((results) => {
winston.warn(JSON.stringify(results, null, 2));
res.status(200)
.send(results);
})
.catch(error => res.status(500)
.send({ error: error.toString() }));
But when I execute it I have an error like:
{
"error": "SequelizeEagerLoadingError: experienceTag is not associated to experience!"
}
I think you like to include Tag rather than ExperienceTag, the following example may help you
Experience.findAll({
include: [{
model: Tag, //model name which you want to include
as: 'Tags', // you have to pass alias as you used while defining
where: { tagId: 44 },
}],
})
I think , you need to add as: 'Experiences' , in your include as you have defined association with alias
Change this
Experience.findAll({
include: [{
model: ExperienceTag,
where: { tagId: 44 },
}],
})
With
Experience.findAll({
include: [{
model: ExperienceTag,
as: 'Experiences', // <---- HERE
where: { tagId: 44 },
}],
})

Categories