i am using PostgreSQL with Sequelize ORM to create my db.
I have this models:
models.js
const Users = db.define("users", {
name: {
type: DataTypes.STRING,
},
lastname: {
type: DataTypes.STRING,
},
sector: {
type: DataTypes.STRING,
},
email: { type: DataTypes.STRING, unique: true, allowNull: false },
password: { type: DataTypes.STRING, allowNull: false },
points: { type: DataTypes.INTEGER, defaultValue: 0 },
suscripcion: { type: DataTypes.BOOLEAN, defaultValue: false },
preference_id: { type: DataTypes.STRING },
});
const Pronostico = db.define("pronosticos", {
matchId: {
type: DataTypes.STRING,
unique: true,
},
winner: {
type: DataTypes.STRING,
},
goalHome: {
type: DataTypes.INTEGER,
},
goalAway: {
type: DataTypes.INTEGER,
},
});
//REFRESH TOKEN
const RefreshToken = db.define("refreshTokens", {
token: {
type: DataTypes.STRING,
},
expiryDate: {
type: DataTypes.DATE,
},
userId: {
type: DataTypes.STRING,
},
});
RefreshToken.createToken = async function (user) {
let expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + config.jwtRefreshExpiration);
let _token = uuidv4();
let refreshToken = await this.create({
token: _token,
userId: user.id,
expiryDate: expiredAt.getTime(),
});
return refreshToken.token;
};
RefreshToken.verifyExpiration = (token) => {
return token.expiryDate.getTime() < new Date().getTime();
};
This are the Relationships:
Users.hasMany(Pronostico, { as: "pronosticos" });
Pronostico.belongsTo(Users, { foreignKey: "userId", as: "user" });
RefreshToken.belongsTo(User, {
foreignKey: 'userId', targetKey: 'id'
});
User.hasOne(RefreshToken, {
foreignKey: 'userId', targetKey: 'id'
});
Somewhere on my server, I have this controller which creates a refreshToken:
let refreshToken = await RefreshToken.createToken(user);
The problem is that I get an error that says "column userId doesnt exist in refreshTokens relationship.
Maybe I have some issues with the relationships but I think they are OK.
Any suggestion?
Related
While trying to save data into postgres database using sequelize BlogModel.create() system failed to save the data into table and server is returning columns createdat, updatedat, multiple times in console. ( please see below ). In the scheme I have added the column only once, can someone advise on this issue here ?
Executing (default): INSERT INTO "userBlogs" ("id","email","blogdetails","tags","createdat","updatedat","createdAt","updatedAt") VALUES (DEFAULT,$1,$2,$3,$4,$5,$6,$7) RETURNING "id","email","blogdetails","tags","createdat","updatedat","createdAt","updatedAt";
//userBlogs.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const userBlogs = sequelize.define('userBlogs', {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
email: {
type: DataTypes.STRING(255),
allowNull: false
},
blogdetails: {
type: DataTypes.TEXT,
allowNull: false
},
tags: {
type: DataTypes.STRING(255),
allowNull: false
},
createdat: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
},
updatedat: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
}
}, {
timestamps: true,
tableName: 'userBlogs'
});
return userBlogs;
};
//server.js
const usersBlogSchema = require('./modals/userBlogs');
const BlogModel = usersBlogSchema(sequelize, DataTypes);
app.post('/service/createblogs', async (req, res, next)=> {
try {
const userEmail = req.body.email;
const blogDetails = req.body.blogValue;
const tags = req.body.tagValue;
if (Object.keys(req.body).length === 0) {
res.status(403).json({ fail: "Invalid blog request or blog request is blank !" });
} else {
var requestData = {email:userEmail, blogdetails:blogDetails, tags:tags };
const createBlogRequest = await BlogModel.create(requestData);
res.status(200).json({ success: true });
}
} catch (e) {
console.log(e)
return next(e);
}
});
Returning createdAt and updatedAt multiple times because you have added columns (createdAt and updatedAt )and also timestamps:true ,
timestamps also adds these both columns
use either columns or timestamps
'use strict';
module.exports = (sequelize, DataTypes) => {
const userBlogs = sequelize.define('userBlogs', {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
email: {
type: DataTypes.STRING(255),
allowNull: false
},
blogdetails: {
type: DataTypes.TEXT,
allowNull: false
},
tags: {
type: DataTypes.STRING(255),
allowNull: false
},
}, {
timestamps: true,
tableName: 'userBlogs'
});
return userBlogs;
};
I have a MySql DB and using sequelize.
I have a recipe and ingredients tables.
I want to pass the ingredients as an array to the api.
So I researched and discovered I can use get/set to achieve this.
But I get an "Unknown coumn 'ingredients' in 'field list'".
This is my model. The line
console.info("getDataValue...", this);
never gets executed.
function model(sequelize) {
const attributes = {
recipeTitle: { type: DataTypes.STRING(255), allowNull: false },
category: { type: DataTypes.STRING(30), allowNull: false },
recipeSource: { type: DataTypes.STRING(100), allowNull: false },
recipeSourceData: { type: DataTypes.TEXT(), allowNull: true },
method: { type: DataTypes.TEXT(), allowNull: true },
comments: { type: DataTypes.TEXT(), allowNull: true },
prepTime: { type: DataTypes.STRING(10), allowNull: true },
cookTime: { type: DataTypes.STRING(10), allowNull: true },
rating: { type: DataTypes.FLOAT, allowNull: false },
owner_id: { type: DataTypes.INTEGER, allowNull: false },
ingredients: {
type: DataTypes.TEXT,
get() {
console.info("getDataValue...", this);
return JSON.parse(this.getDataValue("ingredients"));
},
set(val) {
if (!Array.isArray(val)) {
throw new Error("ingredients must to be an array");
}
this.setDataValue("ingredients", JSON.stringify(val));
},
},
};
This is my validate-request middle ware and it does have the ingredients
when i console.info("valreq...").
So it seems its the schema.validate that fails??
function validateRequest(req, next, schema) {
console.info("valreq...", req.body);
const options = {
abortEarly: false, // include all errors
allowUnknown: true, // ignore unknown props
stripUnknown: true, // remove unknown props
};
const { error, value } = schema.validate(req.body, options);
if (error) {
next(`Validation error: ${error.details.map((x) => x.message).join(", ")}`);
} else {
console.info("value...", value);
req.body = value;
next();
}
}
I'm new to sequelize as a user and I use the 'many to many' option in the team situation. I created my code but : user_team is not associated to team! i am getting error how can i fix it. I'm doing it for a task, I would be very happy if you help me.tanks
If the structure is also wrong, can you tell me what my mistakes are?
userteam.js
module.exports = (sequelize, DataTypes) => {
const UserTeam = sequelize.define(
"user_team",
{
user_team_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
user_id: {
type: DataTypes.INTEGER,
primaryKey: false,
references: {
model: "user",
key: "user_id",
},
onDelete: "cascade",
onUpdate: "cascade",
unique: "unique-team-per-user",
},
team_id: {
type: DataTypes.INTEGER,
primaryKey: false,
references: {
model: "team",
key: "team_id",
},
onDelete: "cascade",
onUpdate: "cascade",
unique: "unique-team-per-user",
},
},
{ timestamps: false, tableName: "user_team", underscored: true }
);
UserTeam.associate = (models) => {
UserTeam.belongsTo(models.User, {
foreignKey: "user_id",
targetKey: "user_id",
as: "User",
});
UserTeam.belongsTo(models.Team, {
foreignKey: "team_id",
targetKey: "team_id",
as: "Team",
});
};
return UserTeam;
};
user.js
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"user",
{
user_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
},
{ timestamps: true, tableName: "user", underscored: true }
);
User.associate = (models) => {
User.hasMany(models.Todo, {
as: "todos",
foreignKey: "userId",
});
User.hasMany(models.Team, {
as: "teams",
foreignKey: "admin",
});
User.belongsToMany(models.Team, {
as: "TeamsForUser",
through: models.UserTeam,
foreignKey: "user_id",
});
};
return User;
};
team.js
module.exports = (sequelize, DataTypes) => {
const Team = sequelize.define(
"team",
{
team_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
teamName: {
type: DataTypes.STRING,
allowNull: false,
},
admin: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{ tableName: "team", underscored: true }
);
Team.associate = (models) => {
Team.belongsTo(models.User, {
as: "user",
foreignKey: "admin",
});
Team.belongsToMany(models.User, {
as: "UserInTeam",
through: models.UserTeam,
foreignKey: "team_id",
});
};
return Team;
};
controller.js
const getAll = async (req, res, next) => {
try {
const myTeams = await Team.findAll({
include: [{ model: UserTeam }],
});
myTeams.forEach((element) => {
console.log(element.get());
});
return res.status(200).json(myTeams);
} catch (err) {
console.log(err.message);
res.status(500).json({ message: err });
}
};
i solved this problem
just add to index database config js
db.users.belongsToMany(db.team, {
as: "teams",
through: "user_team",
foreignKey: "user_id",
});
db.team.belongsToMany(db.users, {
as: "users",
through: "user_team",
foreignKey: "team_id",
});
enter code here
I'm new to mongoose and i have a problem.
In my app, i have a Travel model like this:
const travelSchema = new mongoose.Schema({
title: {
type: String,
required: [true, 'Please add a title'],
trim: true,
maxlength: [50, 'Title can not be more than 50 characters'],
},
cities: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'City',
},
],
});
and a City model like this :
const citySchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
},
location: {
type: {
type: String,
enum: ['Point'],
required: true,
},
coordinates: {
type: [Number],
required: true,
},
},
travels: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Travel',
},
],
});
So when i delete a travel, i want to remove the travel_id from the 'travels' field of the cities which are concerned by the travel.
Here i am:
exports.deleteTravel = asyncHandler(async (req, res, next) => {
const travel = await Travel.findByIdAndDelete(req.params.id);
travel.cities.map(cityId => {
City.findByIdAndUpdate(
cityId,
{ travels: travels.filter(id => id !== travel._id) },
{
new: true,
runValidators: true,
}
);
});
res.status(200).json({ success: true, data: {} });
});
I got this error message: Error: travels is not defined
Do you have any idea why?
Many thanks !
It's working like this :)
exports.deleteTravel = asyncHandler(async (req, res, next) => {
const travel = await Travel.findByIdAndDelete(req.params.id);
travel.cities.map(async cityId => {
await City.findByIdAndUpdate(
cityId,
{ $pull: { travels: travel._id } },
{
new: true,
runValidators: true,
}
);
});
I'm having some trouble trying to save an array inside an array of objects.
I'm getting the following response from the server:
{ [CastError: Cast to embedded failed for value "\'maxbeds: 4\'" at path "saved_searches"]
message: 'Cast to embedded failed for value "\\\'maxbeds: 4\\\'" at path "saved_searches"',
name: 'CastError',
kind: 'embedded',
value: '\'maxbeds: 4\'',
path: 'saved_searches',
reason: [TypeError: Cannot use 'in' operator to search for '_id' in maxbeds: 4] }
Here's my Schema:
var mongoose = require('mongoose'),
rfr = require('rfr'),
passwordHelper = rfr('server/helpers/password.js'),
Schema = mongoose.Schema,
_ = require('lodash');
/*
*
* Creating UserSchema for MongoDB
*
*/
var UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
select: false
},
name: {
type: String,
required: true
},
passwordSalt: {
type: String,
required: true,
select: false
},
saved_houses: [{
mlsId: {
type: String
},
addressFull: {
type: String
},
bedrooms: {
type: Number
},
listPrice: {
type: Number
},
bathrooms: {
type: Number
},
sqft: {
type: Number
},
createdAt: {
type: Date,
default: Date.now
}
}],
saved_searches: [{
search_name: {
type: String
},
filters: {
type: [Schema.Types.Mixed]
},
createdAt: {
type: Date,
default: Date.now
}
}],
active: {
type: Boolean,
default: true
},
createdAt: {
type: Date,
default: Date.now
}
});
// compile User model
module.exports = mongoose.model('User', UserSchema);
The problem, I believe is the filters array that live inside an object inside the saved_searches array
Now, in my router I do the following:
var express = require('express'),
savedDataRouter = express.Router(),
mongoose = require('mongoose'),
rfr = require('rfr'),
s = rfr('server/routes/config/jwt_config.js'),
User = rfr('server/models/User.js'),
jwt = require('jsonwebtoken');
savedDataRouter.post('/searches', function (req, res) {
if (mongoose.Types.ObjectId.isValid(req.body.userId)) {
User.findByIdAndUpdate({
_id: req.body.userId
}, {
$push: {
saved_searches: {
search_name: req.body.search_name,
$each: req.body.filters
}
},
}, {
new: true
},
function (err, doc) {
if (err || !doc) {
console.log(err);
res.json({
status: 400,
message: "Unable to save search." + err
});
} else {
return res.json(doc);
}
});
} else {
return res.status(404).json({
message: "Unable to find user"
});
}
});
If I log the request body coming from the client I get the following:
//console.log(req.body)
{ search_name: 'Sarasota',
filters: [ 'minbaths: 1', 'maxbaths: 3', 'minbeds: 2', 'maxbeds: 4' ],
userId: '583359409a1e0167d1a3a2b3' }
I've tried all the things I've seen in Stack Overflow and other online resources with no luck. What am I doing wrong?
Edit
Added module dependencies to my UserSchema and SavedDataRouter
try this
User.findByIdAndUpdate({
_id: req.body.userId
}, {
$push: {
saved_searches: {
search_name: req.body.search_name,
filters: req.body.filters
}
},
}, {
new: true
},
function (err, doc) {
if (err || !doc) {
console.log(err);
res.json({
status: 400,
message: "Unable to save search." + err
});
} else {
return res.json(doc);
}
});