I am able to create records in my MySQL DB with sequelize and NodeJS.
But now I am trying to update records in my Database.
I have NodeJS as backend and my DB is MySql. Sequelize is my ORM. In Sequelize 5, I have a couple of classes: WorkOder, User (mechanic), Customer, Client and ExpertiseOffice. My datamodel is not complex, there are only 1:1 relations. A WorkOrder has one customer, one Client and one ExpertiseOffice.
I use Postman to test my api's. With creating a WorkOrder with some Customer fields included the workOrder is created but not the Customer.
My associations file looks like this:
const User = require('../models/user');
const WorkOrder = require('../models/work-order');
const Customer = require('../models/customer');
const Client = require('../models/client');
const ExpertiseOffice = require('../models/expertise-office');
WorkOrder.belongsTo(User, { foreignKey: 'mechanicId' });
WorkOrder.belongsTo(Client, { foreignKey: 'clientId' });
WorkOrder.belongsTo(Customer, { foreignKey: 'customerId' });
WorkOrder.belongsTo(ExpertiseOffice, { foreignKey: 'expertiseOfficeId' });
The WorkOrder model looks like this:
// WORK-ORDER MODEL
const Customer = require('./customer');
const Client = require('./client');
const ExpertiseOffice = require('./expertise-office');
const User = require('./user');
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const WorkOrder = sequelize.define('workOrders', {
id: {
type: Sequelize.UUID,
allowNull: false,
primaryKey: true,
},
projectNumber: {
type: Sequelize.INTEGER,
allowNull: true,
},
dateInspection: {
type: Sequelize.DATE,
allowNull: true,
},
mechanicId: {
type: Sequelize.UUID,
allowNull: true,
references: {
// User belongsTo WorkOrder 1:1
model: 'User',
key: 'id',
},
},
clientId: {
// Opdrachtgever
type: Sequelize.UUID,
allowNull: true,
references: {
// Client belongsTo WorkOrder 1:1
model: 'Client',
key: 'id',
},
},
customerId: {
// klant
type: Sequelize.UUID,
allowNull: true,
references: {
// Customer belongsTo WorkOrder 1:1
model: 'Customer',
key: 'id',
},
},
expertiseOfficeId: {
type: Sequelize.UUID,
allowNull: true,
references: {
// ExpertiseOffice belongsTo WorkOrder 1:1
model: 'ExpertiseOffice',
key: 'id',
},
},
leakageReason: {
type: Sequelize.STRING,
allowNull: true,
},
status: {
type: Sequelize.STRING,
allowNull: true,
},
// Timestamps
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
});
module.exports = WorkOrder;
In the front end application only very limited fields are required because the front end user can add information about the customer, client etc. on a later moment.
My WorkOrder controller with the updatre workOrder code (not working properly) is looking like this.
exports.updateWorkOrder = (req, res, next) => {
console.log('####-in the updateWorkOrder endpoint!');
const workOrder = req.body;
console.log('####-put-workorder', workOrder);
WorkOrder.update(
workOrder,
{ where: { id: req.params.id } },
{ include: [User, Customer, Client, ExpertiseOffice] }
)
.then((result) => {
if (result) {
WorkOrder.findByPk(req.params.id).then((result) => {
console.log('####--result', result);
console.log('####-work-order updated!');
res.status(200).json({
message: 'Work order successfully updated!',
data: result,
});
});
}
})
.catch((err) => {
console.log('error', err);
res.status(500).json({
message: 'An error occurred',
err: err,
});
});
};
The workOrder data which is going into the update method looks like this:
####-in the updateWorkOrder endpoint!
####-put-workorder {
id: '29d9795d-ef7f-418e-a479-340cb7ee5509',
projectNumber: '123456',
dateInspection: null,
followupInspection: null,
clientPresent: null,
mechanicId: null,
clientId: '2c611177-48f6-48d2-a2d0-e7f6a93cc16b',
customerId: 'd53f56c7-9954-4e52-b8e2-de4d28229caf',
expertiseOfficeId: null,
leakageReason: 'issue with roof',
visibleWaterDamage: null,
visibleWaterDamagePeriod: null,
buildingType: null,
renovatedYear: null,
status: null,
createdAt: '2020-07-04T07:24:28.000Z',
updatedAt: '2020-07-04T07:25:03.000Z',
user: null,
customer: {
id: 'd53f56c7-9954-4e52-b8e2-de4d28229caf',
name: 'Customer One',
contactPerson: null,
companyName: null,
street: 'Street',
houseNumber: '1',
houseNumberExt: null,
zipCode: '91111',
city: 'LA',
phoneNumber: null
},
client: {
id: '2c611177-48f6-48d2-a2d0-e7f6a93cc16b',
name: 'Roof Inspectors',
contactPerson: null,
email: null,
phoneNumber: 'Roof Inspectors',
street: null,
houseNumber: null,
houseNumberExt: null,
zipCode: null,
city: null,
attribute: null
},
expertiseOffice: null
}
This is the correct updated information from the front end.
Now I don't get an error message from sequelize but the record is not updated.
The spooled result looks like this:
####--result workOrders {
dataValues: {
id: '29d9795d-ef7f-418e-a479-340cb7ee5509',
projectNumber: '123456',
dateInspection: null,
followupInspection: null,
clientPresent: null,
mechanicId: null,
clientId: '2c611177-48f6-48d2-a2d0-e7f6a93cc16b',
customerId: 'd53f56c7-9954-4e52-b8e2-de4d28229caf',
expertiseOfficeId: null,
leakageReason: 'issue with roof',
visibleWaterDamage: null,
visibleWaterDamagePeriod: null,
buildingType: null,
renovatedYear: null,
status: null,
createdAt: 2020-07-04T07:24:28.000Z,
updatedAt: 2020-07-04T08:06:47.000Z
},
_previousDataValues: {
id: '29d9795d-ef7f-418e-a479-340cb7ee5509',
projectNumber: '123456',
dateInspection: null,
followupInspection: null,
clientPresent: null,
mechanicId: null,
clientId: '2c611177-48f6-48d2-a2d0-e7f6a93cc16b',
customerId: 'd53f56c7-9954-4e52-b8e2-de4d28229caf',
expertiseOfficeId: null,
leakageReason: 'issue with roof',
visibleWaterDamage: null,
visibleWaterDamagePeriod: null,
buildingType: null,
renovatedYear: null,
status: null,
createdAt: 2020-07-04T07:24:28.000Z,
updatedAt: 2020-07-04T08:06:47.000Z
},
_changed: {},
_modelOptions: {
timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: { id: '29d9795d-ef7f-418e-a479-340cb7ee5509' },
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: { plural: 'workOrders', singular: 'workOrder' },
omitNull: false,
sequelize: Sequelize {
options: [Object],
config: [Object],
dialect: [MysqlDialect],
queryInterface: [QueryInterface],
models: [Object],
modelManager: [ModelManager],
connectionManager: [ConnectionManager],
importCache: {}
},
hooks: {}
},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [
'id',
'projectNumber',
'dateInspection',
'followupInspection',
'clientPresent',
'mechanicId',
'clientId',
'customerId',
'expertiseOfficeId',
'leakageReason',
'visibleWaterDamage',
'visibleWaterDamagePeriod',
'buildingType',
'renovatedYear',
'status',
'createdAt',
'updatedAt'
]
},
isNewRecord: false
}
Can anybody please help me? I have no clue why the records is not updated.
Many thanks in advance.
Pete
Related
i have a little problem. i'm making my backend in nodeJS, i use sequelize for implement database.
here the schema for DB:
DB Schema
my problem is in the mapPoint table and game table.
here is my server :
game.model.js
module.exports = (sequelize, Sequelize) => {
const Game = sequelize.define("games", {
name: {
type: Sequelize.STRING,
allowNull: false
},
latitude: {
type: Sequelize.FLOAT,
allowNull: false
},
longitude: {
type: Sequelize.FLOAT,
allowNull: false
}
});
return Game;
};
mapPoint.model.js
module.exports = (sequelize, Sequelize) => {
const MapPoint = sequelize.define("mapPoints", {
latitude: {
type: Sequelize.FLOAT,
allowNull: false
},
longitude: {
type: Sequelize.FLOAT,
allowNull: false
}
});
return MapPoint
};
my create function
exports.create = (req, res) => {
// Save User to Database
Game.create({
name: req.body.name,
latitude: req.body.latitude,
longitude: req.body.longitude,
userId: req.body.userId
})
.then((mapPoints) => {
console.log("------------- in .then")
if (req.body.mapPoints) {
console.log("------------- in if")
MapPoint.create(
console.log("------------- in create"),
{
latitude: req.body.latitude,
longitude: req.body.longitude
})
.then(() => {
console.log('xxxxx: ' + mapPoints);
game.addMapPoints(mapPoints)
.then(() => {
res.send({message: "MapPoint was added successfully"})
})
})
}
});
};
and relation 1:N between the game table and mapPoint table
// mapPoint -> game
db.game.hasMany(db.mapPoint, { as: "mapPoints"});
db.mapPoint.belongsTo(db.game, {
foreignKey: "gameId",
as: "game"
});
when i post json on postman, he send me error
postman: postman
the error:
/Users/arktik92/Desktop/CatServer/node_modules/sequelize/lib/instance-validator.js:50
throw new sequelizeError.ValidationError(null, this.errors);
^
ValidationError [SequelizeValidationError]: notNull Violation: mapPoints.latitude cannot be null,
notNull Violation: mapPoints.longitude cannot be null
at InstanceValidator._validate (/Users/arktik92/Desktop/CatServer/node_modules/sequelize/lib/instance-validator.js:50:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async InstanceValidator._validateAndRunHooks (/Users/arktik92/Desktop/CatServer/node_modules/sequelize/lib/instance-validator.js:60:7)
at async InstanceValidator.validate (/Users/arktik92/Desktop/CatServer/node_modules/sequelize/lib/instance-validator.js:54:12)
at async model.save (/Users/arktik92/Desktop/CatServer/node_modules/sequelize/lib/model.js:2368:7)
at async Function.create (/Users/arktik92/Desktop/CatServer/node_modules/sequelize/lib/model.js:1344:12) {
errors: [
ValidationErrorItem {
message: 'mapPoints.latitude cannot be null',
type: 'notNull Violation',
path: 'latitude',
value: null,
origin: 'CORE',
instance: mapPoints {
dataValues: {
id: null,
updatedAt: 2022-12-01T11:30:06.247Z,
createdAt: 2022-12-01T11:30:06.247Z
},
_previousDataValues: {},
uniqno: 1,
_changed: Set(0) {},
_options: {
isNewRecord: true,
_schema: null,
_schemaDelimiter: '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined
},
isNewRecord: true
},
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
},
ValidationErrorItem {
message: 'mapPoints.longitude cannot be null',
type: 'notNull Violation',
path: 'longitude',
value: null,
origin: 'CORE',
instance: mapPoints {
dataValues: {
id: null,
updatedAt: 2022-12-01T11:30:06.247Z,
createdAt: 2022-12-01T11:30:06.247Z
},
_previousDataValues: {},
uniqno: 1,
_changed: Set(0) {},
_options: {
isNewRecord: true,
_schema: null,
_schemaDelimiter: '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined
},
isNewRecord: true
},
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
}
]
}
[nodemon] app crashed - waiting for file changes before starting...
can you help me please ?
I am creating a chat application and trying to create a relationship between User and User through friendship. So far I can create a relationship, but in the end only one user assigned a friend. I'm using Express, sequalize with postgress deployed to heroku. I don't know how to achieve it, any help is appreciated
migration:
`enter code here`await queryInterface.createTable('users', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, } }, }); await queryInterface.createTable('friendships', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, }, user: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'id' }, }, friend: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'id' }, }, status: { type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'), allowNull: false, defaultValue: 'PENDING', }, });
friendship model:
Friendship.init(
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
user: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
friend: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
status: {
type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'),
allowNull: false,
defaultValue: 'PENDING',
},
},
{
sequelize,
underscored: true,
timestamps: false,
modelName: 'friendship',
}
);
associations:
User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user',
otherKey: 'friend' });
Friendship.belongsTo(User, { as: 'info', foreignKey: 'friend' });
controller:
export const addFriend = async (req: Request, res: Response) => {
try {
const { friendId } = req.body;
const userId = req.decodedToken?.id;
const friend = await User.findByPk(friendId, {
attributes: { exclude: ['passwordHash'] },
include: [{ model: User, as: 'friends' }],
});
if (friend)
await Friendship.create({
user: userId,
friend: friend.id,
status: 'PENDING',
});
return res.status(200).json({ status: 'success' });
} catch (e) {
res.status(500).json({ error: 'The server cannot create the user' });
console.log(e);
}
};
response:
"users": {
"count": 2,
"rows": [
{
"id": "e7c7ce39-953a-45e7-a892-a5f99554382e",
"email": "admin",
"username": "admin",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friends": [
{
"id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"email": "admin2",
"username": "admin",
"passwordHash": "$2b$10$GajlewYeiGvUOOV08YOzLuedV/8.KJNUeHB4WPKlUFxErj91ljfWq",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friendship": {
"id": "a78b9336-f5a6-4153-b3e1-e44dbe1cc7a6",
"user": "e7c7ce39-953a-45e7-a892-a5f99554382e",
"friend": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"status": "PENDING"
}
}
]
},
{
"id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"email": "admin2",
"username": "admin",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friends": []
}
Edit:
I made something like this, it's not perfect, but it's good for me
User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user' });
User.belongsToMany(User, { as: 'friend', through: Friendship, foreignKey: 'friend' });
Please consider a many to many relationship.
An user can be a friend of many users.
Many users can be friends of one user.
You may found the how-to implement in the official doc: here.
Basically, use belongsToMany in both associations:
Implementation
The main way to do this in Sequelize is as follows:
const Movie = sequelize.define('Movie', { name: DataTypes.STRING });
const Actor = sequelize.define('Actor', { name: DataTypes.STRING });
Movie.belongsToMany(Actor, { through: 'ActorMovies' });
Actor.belongsToMany(Movie, { through: 'ActorMovies' });
when i do a create like this
const user = User.create();
if i print user on console the ID it return undefined, the data was inserted on the database but the id return as undefined.
I am using sequelize v6 and mariadb
My User model:
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
email_id: {
type: DataTypes.UUID,
defaultValue: null
},
auth_id: {
type: DataTypes.UUID,
defaultValue: null
}
}, {
tableName: 'user'
});
User.associate = function(models) {
User.hasOne(models.UserEmail, {foreignKey: 'email_id', as: 'email'}),
User.hasOne(models.UserAuth, {foreignKey: 'auth_id', as: 'auth'})
};
return User;
};
This is the console.log result
User {
dataValues: {
id: undefined,
updatedAt: 2021-11-10T11:37:08.793Z,
createdAt: 2021-11-10T11:37:08.793Z
},
_previousDataValues: {
id: undefined,
createdAt: 2021-11-10T11:37:08.793Z,
updatedAt: 2021-11-10T11:37:08.793Z
},
_changed: Set(0) {},
_options: {
isNewRecord: true,
_schema: null,
_schemaDelimiter: '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined
},
isNewRecord: false
}
What's wrong with the api or router? I definitely included the user model Why is no user information included? Below is the api logic for loading an existing post.
Since the author information is also required, the user model information is included using the include syntax below.
User information is not printed.
What is the reason?
git
https://github.com/hyunsokstar/node_bird_22
api code
router.get('/', async (req, res, next) => { // GET /api/posts
try {
const posts = await db.Post.findAll({
include: [{
model: db.User,
attributes: ['id', 'nickname'],
}],
order: [['createdAt', 'DESC']], // DESC는 내림차순, ASC는 오름차순
});
console.log("posts : ", posts);
res.json(posts);
} catch (e) {
console.error(e);
next(e);
}
});
model
// back\models\post.js
module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('Post', { // 테이블명은 posts
content: {
type: DataTypes.TEXT, // 매우 긴 글
allowNull: false,
},
}, {
charset: 'utf8mb4', // 한글+이모티콘
collate: 'utf8mb4_general_ci',
});
Post.associate = (db) => {
db.Post.belongsTo(db.User); // 테이블에 UserId 컬럼이 생겨요
db.Post.hasMany(db.Comment);
db.Post.hasMany(db.Image);
// 릴레이션 관계 추가
db.Post.belongsTo(db.Post, { as: 'Retweet' }); // RetweetId 컬럼 생성
db.Post.belongsToMany(db.Hashtag, { through: 'PostHashtag' });
db.Post.belongsToMany(db.User, { through: 'Like', as: 'Likers' });
};
return Post;
};
result
Post {
dataValues:
{ id: 21,
content: 'write test',
createdAt: 2019-11-07T09:43:00.000Z,
updatedAt: 2019-11-07T09:43:00.000Z,
UserId: 1,
RetweetId: null,
User: [User] },
_previousDataValues:
{ id: 21,
content: 'write test',
createdAt: 2019-11-07T09:43:00.000Z,
updatedAt: 2019-11-07T09:43:00.000Z,
UserId: 1,
RetweetId: null,
User: [User] },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: [Object],
omitNull: false,
charset: 'utf8mb4',
collate: 'utf8mb4_general_ci',
sequelize: [Sequelize],
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [Array],
includeNames: [Array],
includeMap: [Object],
includeValidated: true,
attributes: [Array],
raw: true },
isNewRecord: false,
User:
User {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false } } ]
const where = {};
let options = { where };
options.include = [
{
model: db.User,
attributes: ['id', 'nickname'],
},
];
options.order = [['createdAt', 'DESC']];
const posts = await db.Post.findAll(options);
Try this it will help
Here is code for User model with JOI (14.3) validation. The code used to be working when creating new user but it seems got flu recently and throws out error of xxx not allowed:
require('dotenv').config({path: process.cwd() +'\\config\\.env'});
const jwt = require('jsonwebtoken');
const moment = require('moment');
const Joi = require('joi');
const Sql = require('sequelize');
const db = require("../startup/db");
const User = db.define('user', {
name: {type: Sql.STRING,
allowNull: false,
min: 2,
max: 50,
},
email: {type: Sql.STRING,
isEmail: true
},
cell: {type: Sql.STRING,
allowNull: false,
min: 10,
max: 20,
},
cell_country_code: {type: Sql.STRING,
allowNull: false
},
comp_name: {type: Sql.STRING
},
status: {type: Sql.STRING,
allowNull: false,
isIn: ['active', 'blocked', 'inactive', 'pending', 'unverified']
},
role: {type: Sql.STRING,
allowNull: false
},
device_id: {type: Sql.STRING, //maybe empty when the user is initially created.
},
user_data: {type: Sql.JSONB
},
last_updated_by_id: {type: Sql.INTEGER},
fort_token: {type: Sql.STRING,
allowNull: false,
min: 20 //64 for production
},
createdAt: Sql.DATE,
updatedAt: Sql.DATE
}, {
indexes: [
{
//For same fort_token, name to be unique
unique: true,
fields: ['name', 'fort_token']
}, {
//unique cell
//unique: true,
fields: ['cell_country_code', 'cell', 'status']
}, {
fields: ['cell_country_code', 'cell']
}, {
//email
fields: ['email']
}, {
fields: ['device_id']
}, {
fields: ['status']
}, {
fields: ['fort_token']
}
]
});
function validateUser(user) {
const schema = {
name: Joi.string()
.min(2)
.max(50)
.required()
.trim(),
cell: Joi.string()
.min(10)
.max(20)
.trim()
.required()
.error(new Error('该手机号有误!')),
cell_country_code: Joi.string()
.trim()
.required(),
role: Joi.string()
.required()
.trim(),
email: Joi.string()
.email()
.allow("")
.optional()
};
return Joi.validate(user, schema);
};
Here is the error:
new user data : { _device_id: '8c9c25711c7d0262',
cell: '8008006414 ',
cell_country_code: '1',
name: 'ss9',
corp_name: '',
role: 'eventer',
email: '',
user_data: { avatar: '' } }
error in user validate : { ValidationError: "dataValues" is not allowed. "_previousDataValues" is not allowed. "_changed" is not allowed. "_modelOptions" is not allowed. "_options" is not allowed. "isNewRecord" is not allowed
at Object.exports.process (C:\d\code\js\emps_bbone\node_modules\joi\lib\errors.js:203:19)
at internals.Object._validateWithOptions (C:\d\code\js\emps_bbone\node_modules\joi\lib\types\any\index.js:764:31)
at module.exports.internals.Any.root.validate (C:\d\code\js\emps_bbone\node_modules\joi\lib\index.js:147:23)
at validateUser (C:\d\code\js\emps_bbone\models\user.js:106:16)
at router.post (C:\d\code\js\emps_bbone\routes\users.js:217:27)
at newFn (C:\d\code\js\emps_bbone\node_modules\express-async-errors\index.js:16:20)
at Layer.handle [as handle_request] (C:\d\code\js\emps_bbone\node_modules\express\lib\router\layer.js:95:5)
at next (C:\d\code\js\emps_bbone\node_modules\express\lib\router\route.js:137:13)
at C:\d\code\js\emps_bbone\middleware\auth_role.js:7:7
at newFn (C:\d\code\js\emps_bbone\node_modules\express-async-errors\index.js:16:20)
at Layer.handle [as handle_request] (C:\d\code\js\emps_bbone\node_modules\express\lib\router\layer.js:95:5)
at next (C:\d\code\js\emps_bbone\node_modules\express\lib\router\route.js:137:13)
at module.exports (C:\d\code\js\emps_bbone\middleware\auth_userinfo.js:106:13)
isJoi: true,
name: 'ValidationError',
details:
[ { message: '"dataValues" is not allowed',
path: [Array],
type: 'object.allowUnknown',
context: [Object] },
{ message: '"_previousDataValues" is not allowed',
path: [Array],
type: 'object.allowUnknown',
context: [Object] },
{ message: '"_changed" is not allowed',
path: [Array],
type: 'object.allowUnknown',
context: [Object] },
{ message: '"_modelOptions" is not allowed',
path: [Array],
type: 'object.allowUnknown',
context: [Object] },
{ message: '"_options" is not allowed',
path: [Array],
type: 'object.allowUnknown',
context: [Object] },
{ message: '"isNewRecord" is not allowed',
path: [Array],
type: 'object.allowUnknown',
context: [Object] } ],
_object:
user {
dataValues:
{ id: null,
name: 'ss9',
cell: '8008006414',
cell_country_code: '1',
email: '',
role: 'eventer' },
_previousDataValues:
{ name: undefined,
cell: '8008006414 ',
cell_country_code: undefined,
email: undefined,
role: undefined },
_changed:
{ name: true,
cell: true,
cell_country_code: true,
email: true,
role: true },
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: [Object],
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [Array],
name: [Object],
omitNull: false,
sequelize: [Sequelize],
hooks: {} },
_options: { isNewRecord: true, _schema: null, _schemaDelimiter: '' },
isNewRecord: true },
annotate: [Function] }
error in new user
Here is the code for creating new user:
try {
user = new User(_.pick(req.body, ["name", "cell", "cell_country_code", "email", "role" ]));
const { error } = validateUser(user); //<<====== throws error with JOI.validate()
console.log("error in user validate : ", error);
if (error) {console.log("error in new user "); return res.status(400).send(error.details[0].message)};
I have no clue what the validation error is about.
You need to pass option with "allowUnknown:true" as the third argument of validate function
https://github.com/hapijs/joi/blob/v15.0.3/API.md#validatevalue-schema-options-callback