I had this code block working with Sequelize v5. But since switching to v6, it seems to be erroring out. I am getting the error: Error: Invalid value { customer_id: 'dg5j5435r4gfd' }.
And here is the code that creates the where condition block:
let whereBlock = {
deleted_at: null,
};
if (args.includeCore) {
if (customerID !== 'all') {
// whereBlock[Op.or] = [
// { customer_id: customerID },
// { customer_id: coreCustomerID },
// ];
whereBlock[Op.or] = [];
whereBlock[Op.or].push({
customer_id: customerID,
});
whereBlock[Op.or].push({ customer_id: coreCustomerID });
}
} else {
whereBlock.customer_id = customerID;
}
I was using the commented code. And then I tried the code below that. Both are producing the same error. But when I remove all that code from the if block and just put in whereBlock.customer_id = customerID;, then it works fine. So I know the issue is how I am constructing the where condition.
Update: As requested, here is my Sheets model where the where clause is being run on.
'use strict';
export default (sequelize, DataTypes) => {
return sequelize.define(
'Sheet',
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
sheet_name: {
type: DataTypes.STRING,
isAlphaNumeric: true,
required: true,
allowNull: true,
len: [3, 80],
},
sheet_file_name: {
type: DataTypes.STRING,
unique: true,
isAlphaNumeric: true,
required: false,
allowNull: true,
},
brand_name: {
type: DataTypes.STRING,
unique: false,
isAlphaNumeric: true,
required: false,
allowNull: true,
},
customer_id: {
// fk in customers table
type: DataTypes.TINYINT(2).UNSIGNED,
required: true,
allowNull: false,
},
chemical_id: {
// fk in loads table
type: DataTypes.SMALLINT.UNSIGNED,
required: true,
allowNull: false,
},
load_id: {
// fk in loads table
type: DataTypes.SMALLINT.UNSIGNED,
required: true,
allowNull: false,
},
active: {
type: DataTypes.BOOLEAN,
required: true,
allowNull: false,
defaultValue: true,
},
created_at: {
type: DataTypes.DATE,
},
updated_at: {
type: DataTypes.DATE,
},
deleted_at: {
type: DataTypes.DATE,
},
},
{
underscored: true,
paranoid: false,
}
);
};
And in my index I have this to associate sheets with customers: db.Sheet.belongsTo(db.Customer);
Also here is the full code where the whereBlock is used, if that helps:
const files = await db.Sheet.findAll({
raw: true,
attributes: [
'sheet_name',
'sheet_file_name',
['brand_name', 'brand'],
'updated_at',
'active',
[Sequelize.col('Chemical.name'), 'chemical'],
[Sequelize.col('Load.value'), 'load'],
],
include: [
{
model: db.Load.scope(null),
required: true,
as: 'Load',
attributes: ['value'],
},
{
model: db.Chemical.scope(null),
required: true,
as: 'Chemical',
attributes: ['name'],
},
],
// model: model,
where: whereBlock,
order: [['active', 'DESC']],
});
TLDR: So here is what it comes down to:
whereBlock = {
deleted_at: null,
customer_id: customerID,
// [Op.or]: [
// { customer_id: customerID },
// { customer_id: coreCustomerID },
// ],
};
That code above works, but the commented code errors out with: Error: Invalid value { customer_id: '123456' }
OK, this is very weird. But I finally figured out the issue!! Was not something I would have thought of, just found it by chance. It was the way I was importing Op from sequelize.
import Op from 'sequelize';
So apparently, that Op object has another object inside it called Op. So when I call my [Op.or], I instead need to do this: [Op.Op.or].
I did try switching my import to import Op.Op from 'sequelize'; and that caused errors. Anyone know how I can properly import the inner object?
Update
OK, so apparently in my other DB files, I was doing the import differently.
export default (db) => {
const Op = db.Sequelize.Op;
That method works to pull in the correct Op object. So there you go. Hopefully this nightmare issue helps someone else in the future.
Related
I have three tables companies, subscriptions and companySubscription. As name defined company can canbuy/have plan or one subscription belongs to many companies.
So in model/schema I have defined as follows:
companies.js
const sequelize = require("../utils/database");
const bcrypt = require("bcrypt");
const { DataTypes, Model } = require("sequelize");
const subscription = require("./subscriptions");
const CompanySubscription = require("./companySubscription");
class companies extends Model {}
companies.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
contactNo: {
type: DataTypes.STRING,
allowNull: true,
},
companySize: {
type: DataTypes.INTEGER,
allowNull: true,
},
},
{ sequelize, modelName: "companies" }
);
subscription.belongsToMany(companies, { through: CompanySubscription });
module.exports = companies;
subscription.js
const sequelize = require("../utils/database");
const { DataTypes, Model } = require("sequelize");
class subscription extends Model {}
subscription.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
subscriptionPlanType: {
type: DataTypes.ENUM,
values: ["Yearly", "Monthly"],
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
memberCount: {
type: DataTypes.INTEGER,
allowNull: false,
},
amount: {
type: DataTypes.FLOAT,
allowNull: false,
},
},
{ sequelize, modelName: "subscription" }
);
module.exports = subscription;
companySubscription.js
const sequelize = require("../utils/database");
const companies = require("./companies");
const subscription = require("./subscriptions");
const { DataTypes, Model } = require("sequelize");
class CompanySubscription extends Model {}
CompanySubscription.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
status: {
type: DataTypes.ENUM,
values: ["active", "inactive"],
},
subscriptionType: {
type: DataTypes.ENUM,
values: ["Yearly", "Monthly"],
},
subscriptionPlanStartDate: {
type: DataTypes.DATE,
},
subscriptionPlanEndDate: {
type: DataTypes.DATE,
},
paidStatus: {
type: DataTypes.ENUM,
values: ["paid", "unpaid"],
},
paidDate: {
type: DataTypes.DATE,
},
},
{ sequelize, modelName: "CompanySubscription" }
);
module.exports = CompanySubscription;
In controller file I am able to manage to insert the data. Below is the code:
const addBIlling = async (req, res) => {
const foundSubcscription = await subscription.create({
subscriptionPlanType: "Monthly",
name: "s1",
memberCount: 15,
amount: 50.55,
});
const foundCompany = await companies.create({
name: "company1",
email: "company1#gmail.com",
contactNo: "87964644",
companySize: 20,
});
const insertedData = await foundSubcscription.addCompany(foundCompany, {
through: {
status: "active",
paidStatus: "paid",
subscriptionType: "Monthly",
subscriptionPlanEndDate: moment().add(1, "months"),
paidDate: moment().add(1, "months"),
},
});
console.log("inserted data ", insertedData);
res.json({ data: insertedData });
};
Now I want to fetch the records from db as which company has bought which subscription plan!
i.e. company name, subscription plan and its active and paid status and plan's expiry date.
I tried below code:
const billingList = async (req, res) => {
const billingData = await CompanySubscription.findAll({
include: [{ model: companies }],
});
console.log("billing data ", billingData);
};
Above code is throwing error "companies is not associated to CompanySubscription!".
Where have I made a mistake?
Don't try to import models to each other's modules directly. Define model registration functions in each model module and use them all to register models in one place/module and for associations you can define associate function inside each registration function and call them after ALL your models are already registered. That way you won't have cyclic dependencies and all associations will be correct.
See my answer here to get an idea how to do it.
I'm actually trying to set a foreign key in my model "Batiment" that references the primary key of the model "Zone". I found the sequelize doc. and tried to use it but I got some errors that i couldn't fix. So here i am to ask for help...
module.exports = (sequelize, Sequelize) => {
const zone = require("../models/Zone.model.js");
var Batiment = sequelize.define("batiment", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
nom: {
type: Sequelize.STRING
},
code_batiment: {
type: Sequelize.STRING,
unique: true
},
d_creation: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
},
d_modification: {
type: Sequelize.DATE
},
},
{
tableName: 'batiment',
createdAt: false,
updatedAt: false,
});
Batiment.associate = (models) => {
Batiment.belongsTo(zone, {foreignKey: 'ZoneID', as: 'ZoneID'});
};
return Batiment;
};
I also found some similar problems on the forum with solutions that i've tried to applicate but with no success.
If someone can explain me what am I doing wrong and what I can do to fix it, I would be very grateful.
I am using the mongoose updateMany() method and I also want to keep it a part of transaction. The documentation shows the example of save() where I can do something like Model.save({session: mySession}) but don't really know how to use it with for example Model.updateMany()
UPDATE:
For example I have two models called SubDomain and Service and they look like this respectively:
SUB-DOMAIN
{
name: {
type: String,
required: true,
},
url: {
type: String,
required: true,
unique: true,
},
services: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Service",
},
],
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
}
SERVICE:
{
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: { type: Number },
tags: { type: Array },
packages: [
{
name: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
},
],
map: { type: String },
isHidden: {
type: Boolean,
required: true,
default: false,
},
sortingOrder: { type: Number },
isForDomain: { type: Boolean, required: false, default: false },
isForSubDomain: { type: Boolean, required: false, default: false },
subDomains: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "SubDomain",
},
],
}
Now the main field here is the services field in SubDomain and subDomains field in Service.
The complicated part😅:
Whenever the user wants to create new service, I want to $push that service's _id into the array of services of all the subDomains inside that new service
And for that, I am using the updateMany() like this:
const sess = await mongoose.startSession();
sess.startTransaction();
const newService = new Service({
_id: mongoose.Types.ObjectId(),
subDomains: req.body.subDomains
...foo
})
await SubDomain.updateMany(
{ _id: { $in: req.body.subDomains } },
{ $push: { services: newService._id } }
);
The problem starts here, of course I can do:
newService.save({session: sess})
but how do I keep my SubDomain's updateMany in the same transaction (i.e sess)
I know my example is difficult to wrap your head around but I have tried to pick a simplest example rather than copying the exact same code which would have been a lot more difficult
I'm new to using Sequelize and for that I strictly follow the documentation here. It is written that we must use hasOne(), hasMany(), belongsTo() in order to add automatically the foreign keys. In my situation: I have a Category and a FAQ model, defined so:
Category.js
const { Sequelize } = require('sequelize');
const sequelize = require('../database/connection');
const Category = sequelize.define('Category', {
id: {
type: Sequelize.DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
categoryShop_id: {
type: Sequelize.DataTypes.UUID,
allowNull: true
},
name: {
type: Sequelize.DataTypes.STRING,
allowNull: false
},
active: {
type: Sequelize.DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},
parent_id: {
type: Sequelize.DataTypes.INTEGER,
allowNull: true
}
});
Category.associate = (models) => {
Category.hasMany(models.faqs, {
onDelete:'CASCADE',
onUpdate:'CASCADE'
});
};
module.exports = Category;
Faq.js
const { Sequelize } = require('sequelize');
const sequelize = require('../database/connection');
const Faq = sequelize.define('Faq', {
id: {
type: Sequelize.DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
question: {
type: Sequelize.DataTypes.TEXT,
allowNull: false
},
answer: {
type: Sequelize.DataTypes.TEXT,
allowNull: false
},
product_id: {
type: Sequelize.DataTypes.STRING,
allowNull: true
},
active: {
type: Sequelize.DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
}
});
Faq.associate = (models) => {
Faq.belongsTo(models.categories, {
foreignKey: {
name: 'category_id',
allowNull: true
}
});
};
module.exports = Faq;
The migrations run without any errors, but I don't see the added columns to the table. What is the reason for this?
Your confusing model and migration code. Your migrations are ok, but lack the right foreign key columns for your associations.
Your association code looks ok but it belongs in your model.
Look at https://sequelizeui.app/ for some example code.
I need to convert my signup_at timestamp to a certain format each time it's selected from the database.
I want to use a getter for this, but it doesn't appear to be returning the modified data. It continues to return the same date object stored in the database.
var moment = require("moment");
var Referral = sequelize.define("referral", {
id: {
allowNull: false,
type: DataTypes.CHAR(24),
unique: true,
primaryKey: true
},
active: {
allowNull: false,
type: DataTypes.BOOLEAN,
defaultValue: true
},
name: {
allowNull: true,
type: DataTypes.STRING
},
method: {
allowNull: true,
type: DataTypes.STRING
},
signup_at: {
allowNull: false,
type: DataTypes.DATE,
get: function() {
return moment(this.getDataValue("signup_at")).format("MM/DD/YYYY");
}
}
});
Referral.findAll({
where: {
active: true
},
raw: true
}).then(function(referrals) {
console.log(referrals);
});
Try the following code
Referral.findAll({
where: {
active: true
},
raw: false
}).then(function (referrals) {
referrals.forEach(function (referral, index, array) {
var value = referral.get();
console.log(value);
});
});
It seems raw = true won't use the getter function.
You may make raw false and call the get explicitly.