i want to stored all the rawmaterialSchema in UsersSchema using objectId - mern

the code follows two Schemas one is userSchema and another is rawMaterialSchema i want to refrence rawmaterialSchema in userSchema using ObjectId
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const rawmaterialSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
maxlength: 32,
Unique: true
},
size: {
type: Number,
required: true,
trim: true,
maxlength: 32
},
partyname: {
type: String,
trim: true,
maxlength: 40,
required: true
},
partyphonenumber: {
type: Number,
maxlength: 10,
trim: true
},
user: {
type: ObjectId,
ref: "User",
required: true
}
}, { timestamps: true });
module.exports = mongoose.model('Rawmaterial', rawmaterialSchema)

If I understood your question correctly you can do it this way
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const rawmaterialSchema = new mongoose.Schema({
name: {
type: Schema.Types.ObjectId, //<----- CHANGED
ref: 'users' //<----- CHANGED
},
size: {
type: Number,
required: true,
trim: true,
maxlength: 32
},
partyname: {
type: String,
trim: true,
maxlength: 40,
required: true
},
partyphonenumber: {
type: Number,
maxlength: 10,
trim: true
},
user: {
type: ObjectId,
ref: "User",
required: true
}
}, { timestamps: true });
module.exports = mongoose.model('Rawmaterial', rawmaterialSchema)
Assuming that you have userSchema with name user
const UserSchema = new Schema({
name: {
...
},
...
});
module.exports = User = mongoose.model("users", UserSchema);

Related

Sequalize association fails (BelongsTo) NodeJs Sequalize

Trying to work with sequalize association ( belongsTo and hasMany() ) but when i tries to query findAll with include the Model which was associated it fails by saying Models are not associated.
User Model
const {DATE, STRING, INTEGER} = require("sequelize");
const {USER} = require("../config/db.config");
module.exports = (sequelize, Sequelize) => {
const User = sequelize.define("Users", {
id: {
primaryKey: true, type: INTEGER, required: true, autoIncrement: true
}, phoneNumber: {
type: STRING, required: true, unique: true
}, firstname: {
type: STRING, required: true
}, middlename: {
type: STRING, required: false
}, region: {
type: STRING, required: true
}, district: {
type: STRING, required: true
}, street: {
type: STRING, required: true
}, lastname: {
type: STRING, required: true,
}, 'type': {
type: STRING, required: true,
}, email: {
type: STRING, required: true, unique: true
}, status: {
type: Sequelize.ENUM("ACTIVE", "NOT-ACTIVE", "SUSPENDED"), defaultValue: "NOT-ACTIVE",
}, createdAt: {
type: DATE,
}, updatedAt: {
type: DATE,
}
});
User.associate = function (models) {
User.hasMany(models.Students, {foreignKey: 'userId', as: 'user'});
}
return User;
};
Student Model
const {DATE, STRING, INTEGER} = require("sequelize");
module.exports = (sequelize, Sequelize) => {
const Student = sequelize.define("Students",
{
id: {
primaryKey: true, type: STRING, required: true
}, userId: {
type: INTEGER, required: true,
}, status: {
type: Sequelize.ENUM("ACTIVE", "NOT-ACTIVE", "SUSPENDED"), defaultValue: "NOT-ACTIVE",
},
level: {
type: STRING, required: true,
}, createdAt: {
type: DATE,
}, updatedAt: {
type: DATE,
}
});
Student.associate = function (models) {
Student.belongsTo(models.Users, {foreignKey: 'userId', as: 'user'})
Student.belongsToMany(models.Classes, {through: 'StudentClass',})
}
return Student;
};
I have tried to query them by using the bellow function but i got nothing
function getAllStudents() {
Student.findAll({include: [{model: User, as: 'user', required: true}]}).then(value => {
console.log(value)
return value;
}).catch(reason => {
console.error(reason)
})
}
But i get the following
Result i get

Creating Associations with sequelize and mysql

I am trying to create seqeulize models in nodejs app on mysql db. However, When I run the codes, foreign keys are not being created as intended.
This are my models:
Category Model
"use strict";
module.exports = (sequelize, DataTypes) => {
const Category = sequelize.define("Category", {
category_id: {
type: DataTypes.STRING(255),
unique: true,
primaryKey: true,
},
name: { type: DataTypes.STRING, unique: true, allowNull: false },
slug: { type: DataTypes.STRING, unique: true, allowNull: false },
created_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal("CURRENT_TIMESTAMP"),
},
updated_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal(
"CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
),
},
});
Category.associate = (models) => {
Category.hasMany(models.Product);
};
return Category;
};
Product Model
"use strict";
module.exports = (sequelize, DataTypes) => {
const Product = sequelize.define("Product", {
product_id: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
slug: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
sku: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
short_description: {
type: DataTypes.TEXT,
allowNull: false,
},
description: {
type: DataTypes.TEXT,
allowNull: false,
},
price: {
type: DataTypes.DECIMAL,
allowNull: false,
min: 1,
},
discount: {
type: DataTypes.DECIMAL,
allowNull: true,
},
quantity: {
type: DataTypes.INTEGER,
},
vat: {
type: DataTypes.DECIMAL,
allowNull: true,
},
tags: {
type: DataTypes.STRING(255),
allowNull: true,
},
rate: {
type: DataTypes.INTEGER,
allowNull: true,
},
points: {
type: DataTypes.INTEGER,
allowNull: true,
},
new: {
type: DataTypes.VIRTUAL,
get() {
var msPerDay = 8.64e7;
// Copy dates so don't mess them up
var x0 = new Date(this.getDataValue("created_at"));
var x1 = new Date();
// Set to noon - avoid DST errors
x0.setHours(12, 0, 0);
x1.setHours(12, 0, 0);
// Round to remove daylight saving errors
return Math.round((x1 - x0) / msPerDay) <= 30;
},
set(value) {
throw new Error("Can't set Product.new property.");
},
},
thumb_image: {
type: DataTypes.STRING,
allowNull: true,
get() {
if (this.getDataValue("thumb_image")) {
return JSON.parse(this.getDataValue("thumb_image"));
}
return [];
},
set(val) {
this.setDataValue("thumbImage", JSON.stringify(val));
},
},
images: {
type: DataTypes.STRING,
allowNull: true,
get() {
if (this.getDataValue("images")) {
return JSON.parse(this.getDataValue("images"));
}
return [];
},
set(val) {
this.setDataValue("images", JSON.stringify(val));
},
},
featured: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
created_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal("CURRENT_TIMESTAMP"),
},
updated_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal(
"CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
),
},
});
Product.associate = (models) => {
Product.belongsTo(models.Category, {
foreignKey: "category_id",
});
Product.belongsTo(models.Brand, {
foreignKey: "brand_id",
});
Product.belongsTo(models.CartItem, {
foreignKey: "cart_id",
});
};
return Product;
};
Brand Model
"use strict";
module.exports = (sequelize, DataTypes) => {
const Brand = sequelize.define("Brand", {
brand_id: {
type: DataTypes.STRING(255),
unique: true,
primaryKey: true,
},
name: { type: DataTypes.STRING, unique: true, allowNull: false },
slug: { type: DataTypes.STRING, unique: true, allowNull: false },
created_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal("CURRENT_TIMESTAMP"),
},
updated_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal(
"CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
),
},
});
Brand.associate = (models) => {
Brand.hasMany(models.Product);
};
return Brand;
};
And these is my Models/index.js file
/* eslint-disable no-undef */
"use strict";
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/../../config/config.js")[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
}
db.sequelize = sequelize;
db.Sequelize = Sequelize;
fs.readdirSync(__dirname)
.filter((file) => {
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.forEach((file) => {
const model = require(path.join(__dirname, file))(
sequelize,
Sequelize.DataTypes
);
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize
.sync({ force: process.env.NODE_ENV === "development" })
.then(() => {
console.log("Drop and re-sync db.");
});
module.exports = db;
Now when I run the server, I expected the products table to have the fields category_id and brand_id. However, am getting additional fields brand_brand_id and category_category_id on the products table.
Besides, I cannot retrieve the categories, brands and products with the include properties when fecthing data.
What I want is to have the products table properly created in the database with the required foreign keys
Since you have customized foreign keys you have to indicate them in both paired associations:
Category.associate = (models) => {
Category.hasMany(models.Product, { foreignKey: "category_id" });
};
Product.associate = (models) => {
Product.belongsTo(models.Category, {
foreignKey: "category_id",
});
Product.belongsTo(models.Brand, {
foreignKey: "brand_id",
});
Product.belongsTo(models.CartItem, {
foreignKey: "cart_id",
});
};
Brand.associate = (models) => {
Brand.hasMany(models.Product, { foreignKey: "brand_id" });
};

Sequelize belongsTo query results in belongsTo called with something that's not a subclass of Sequelize.Model error

I am trying to write a join query using belongsTo but getting error:
Error: LearningCertificateEvent.belongsTo called with something that's
not a subclass of Sequelize.Model
at Function. (/Users/msmexmac/node/msmex-backend/msmex-api/node_modules/sequelize/lib/associations/mixin.js:93:13)
I am trying to fetch events related to learning cerfificate events. I tried every thing but it does not work somehow.
My models are as follows:
LearningCertificate Model
"use strict";
const Sequelize = require("sequelize");
const sequelize = require("../helpers/db");
const LearningCertificateEvent = require("./LearningCertificateEvent");
const LearningCertificate = sequelize.define(
"LearningCertificate",
{
id: {
autoIncrement: true,
type: Sequelize.BIGINT,
primaryKey: true,
},
userId: {
type: Sequelize.INTEGER,
field: "user_id",
},
certificateURL: {
type: Sequelize.STRING,
field: "certificate_url",
},
certificatePNGURL: {
type: Sequelize.STRING,
field: "certificate_png_url",
},
certificateType: {
type: Sequelize.STRING,
field: "certificate_type",
},
createdAt: {
type: Sequelize.BIGINT,
field: "created_at",
},
updatedAt: {
type: Sequelize.BIGINT,
field: "updated_at",
},
},
{
timestamps: false,
tableName: "learning_certificate",
}
);
LearningCertificate.hasMany(LearningCertificateEvent, {
foreignKey: "certificateId",
});
module.exports = LearningCertificate;
The second model is : LearningCertificateEvent Model
"use strict";
const Sequelize = require("sequelize");
const sequelize = require("../helpers/db");
const MsmexEvent = require("./MsmexEvent");
const LearningCertificateEvent = sequelize.define(
"LearningCertificateEvent",
{
id: {
autoIncrement: true,
type: Sequelize.BIGINT,
primaryKey: true,
},
userId: {
type: Sequelize.INTEGER,
field: "user_id",
},
certificateId: {
type: Sequelize.INTEGER,
field: "certificate_id",
},
eventId: {
type: Sequelize.INTEGER,
field: "event_id",
},
createdAt: {
type: Sequelize.BIGINT,
field: "created_at",
},
updatedAt: {
type: Sequelize.BIGINT,
field: "updated_at",
},
},
{
timestamps: false,
tableName: "learning_certificate_event",
}
);
LearningCertificateEvent.belongsTo(MsmexEvent, {
foreignKey: "eventId",
});
// MsmexEvent.hasMany(LearningCertificateEvent, {
// foreignKey: "eventId",
// });
module.exports = LearningCertificateEvent;
And last model is: MsmexEvent Model
"use strict";
const Sequelize = require("sequelize");
const sequelize = require("../helpers/db");
const LearningCertificateEvent = require("./LearningCertificateEvent");
const Event = sequelize.define(
"Event",
{
id: {
autoIncrement: true,
type: Sequelize.BIGINT,
primaryKey: true,
},
identifier: {
type: Sequelize.STRING,
field: "identifier",
},
expertId: {
type: Sequelize.INTEGER,
field: "expert_id",
},
waitList: {
type: Sequelize.BOOLEAN,
field: "waitList",
},
},
{
timestamps: false,
tableName: "msmex_event",
}
);
module.exports = Event;
The query which I have written is as follows:
return LearningCertificate.findAll({
where: {
userId: userId,
},
include: [
{
model: LearningCertificateEvent,
required: true,
include: [
{
model: MsmexEvent,
required: true,
},
],
},
],
order: [["id", "DESC"]],
});
In query however if I replace MsmexEvent with some other table for example User it works fine.
Can some one please help ?

sequelize - how to calculate the value of a column based on the value in other table

There are 2 tables which are users and tutorial.
The relationship:
users(1) : tutorial(Many)
The users table has below column
completeOneOfTheTutorial: {
type: DataTypes.BOOLEAN,
allowNull: false,
...
},
which is true when
isCompleted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is true in one of the tutorials.
If isCompleted is false for all tutorials of the same user, completeOneOfTheTutorial will be false
Example
User table
[
{
id: "user1",
completeOneOfTheTutorial: true
}
,
{
id: "user2",
completeOneOfTheTutorial: false
},
]
tutorial table
[
{
id: "tutorial1",
userId: "user1",
isCompleted: true
}
,
{
id: "tutorial2",
userId: "user1",
isCompleted: false
},
{
id: "tutorial1",
userId: "user2",
isCompleted: false
}
,
{
id: "tutorial2",
userId: "user2",
isCompleted: false
},
]
How should I modify this field in users.model.js
completeOneOfTheTutorial: {
type: DataTypes.BOOLEAN,
allowNull: false,
...
},
users.model.js
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const users = sequelizeClient.define('users', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4,
},
completeOneOfTheTutorial: {
type: DataTypes.BOOLEAN,
allowNull: false,
...
},
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
users.associate = function (models) {
users.hasMany(models.tutorial,{
foreignKey: 'userId'
});
};
return users;
};
tutorial.model.js
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const tutorial = sequelizeClient.define('tutorial', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4
},
isCompleted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
tutorial.associate = function (models) {
tutorial.belongsTo(models.users);
};
return tutorial;
};

Sequelize Eager Loading Error: social_logins not associated to users

Users Model defined like this.
const db = require ('../../config/db_config');
const users = db.sequelize.define('users', {
id: {
type: db.DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
first_name: {
type: db.DataTypes.STRING(150),
},
last_name: {
type: db.DataTypes.STRING(150),
},
email: {
type: db.DataTypes.STRING(256),
required: true,
unique: true
},
password: {
type: db.DataTypes.STRING,
},
student_id: {
type: db.DataTypes.STRING
},
status: {
type: db.DataTypes.BOOLEAN,
required: true,
defaultValue: 0
},
is_deleted: {
type: db.DataTypes.BOOLEAN,
required: true,
defaultValue: 0
},
createdAt: db.DataTypes.DATE,
updatedAt: db.DataTypes.DATE,
});
module.exports = users;
social_logins Model defined like this
const db = require ('../../config/db_config');
const socialLogins = db.sequelize.define('social_logins', {
id: {
type: db.DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
token: {
type: db.DataTypes.STRING
},
tokenType: {
type: db.DataTypes.STRING
},
fb_id: {
type: db.DataTypes.STRING
},
user_id: {
type: db.DataTypes.INTEGER
},
is_deleted: {
type: db.DataTypes.BOOLEAN,
required: true,
defaultValue: false
}
}, { underscored: true, timestamp: true, tableName: 'social_logins' });
module.exports = socialLogins;
User model associated with the social_logins model using belongsTo function
socialLoginsModel.belongsTo(users)
Sequelize throws eagerLoadingError
Error EagerLoadingError [SequelizeEagerLoadingError]: social_logins is
not associated to users!
While running this query given below.
const userModel = require ('./users_model');
const socialLoginModel = require('../social_logins/social_logins_model');
let id = "123456";
let email = "ex#example.com";
userModel.findOne({
where: { email },
include: [{
model: socialLogins,
where: {
fb_id: id
}
}]
});
you should have associations like this based on your model names
socialLogins.belongsTo(users) & users.hasOne(socialLogins)/ users.hasMany(socialLogins) based on your relations being defined in DB