"dataValues" is not allowed by JOI.validate() - node.js

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

Related

ValidationError [SequelizeValidationError]: notNull Violation: mapPoints.latitude cannot be null, notNull Violation: mapPoints.longitude cannot be nul

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 ?

how to create association instance from source instance with sequelize

I have 1:n association User -> Cart, what I want is, I find User by Id then create Cart by that instance and then fill the product_id manually
I'm using sequelize
I have tried get,set,create from this association and none of them worked, it gave me this error
TypeError: user.createCart is not a function
at /home/horus/beginner-html-site-scripted/server/controllers/Cart.controller.ts:21:26
and this is my CartController:
const { product_id } = req.params;
const product = await ProductModel.findByPk(product_id);
if (!product) {
return res.status(401).json({ message: 'product not found' });
}
//#ts-ignore
const userData = req.user;
const user = await UserModel.findByPk(userData.user_id);
if (!user) return res.status(401).json({ message: 'user not found' });
const cart = await user.createCart();
res.status(200).json({ message: '', cartData: user.getCart() });
those are my Models:
Cart Class
export default class Cart
extends Model<InferAttributes<Cart>, InferCreationAttributes<Cart>>
implements CartInterface {
declare cart_id: CreationOptional<string>;
declare quantity: CreationOptional<number>;
declare user_id: string;
}
Cart.init(
{
cart_id: { type: UUID, defaultValue: UUIDV4, primaryKey: true },
quantity: { type: INTEGER, defaultValue: 1 },
user_id: {
type: UUID,
references: {
model: 'Users',
key: 'user_id',
},
},
},
{ sequelize: db, tableName: 'Carts' }
);
User Class
export default class User
extends Model<InferAttributes<User>, InferCreationAttributes<User>>
implements UserInterface {
declare user_id: CreationOptional<string>;
declare firstName: string;
declare lastName: string;
declare email: string;
declare password: string;
declare avatar: string;
declare verificationCode: CreationOptional<string>;
declare passwordResetCode: CreationOptional<string>;
declare verified: CreationOptional<boolean>;
declare isAdmin: CreationOptional<boolean>;
// timestamps!
// createdAt can be undefined during creation
declare createdAt: CreationOptional<Date>;
// updatedAt can be undefined during creation
declare updatedAt: CreationOptional<Date>;
declare createSession: HasManyCreateAssociationMixin<Session, 'user_id'>;
declare createCart: HasOneCreateAssociationMixin<CartModel>;
declare setCart: HasOneSetAssociationMixin<CartModel, 'cart_id'>;
declare getCart: HasOneGetAssociationMixin<CartModel>;
}
User.init(
{
user_id: {
primaryKey: true,
allowNull: false,
type: UUID,
defaultValue: UUIDV4,
},
firstName: { type: new STRING(128), allowNull: false },
lastName: { type: new STRING(128), allowNull: false },
email: { type: new STRING(128), allowNull: false, unique: true },
password: {
type: new STRING(128),
allowNull: false,
},
avatar: { type: new STRING(128), defaultValue: '' },
verificationCode: { type: UUID, allowNull: false, defaultValue: UUIDV4 },
passwordResetCode: { type: UUID, allowNull: false, defaultValue: '' },
verified: { type: BOOLEAN, defaultValue: false, allowNull: false },
isAdmin: { type: BOOLEAN, defaultValue: false, allowNull: false },
createdAt: DATE,
updatedAt: DATE,
},
{
sequelize: db,
tableName: 'Users',
}
);
user Data
User {
dataValues: {
user_id: '20b42b70-f777-420b-b15b-cbf3732c1a9b',
firstName: 'leo',
lastName: 'qal',
email: 't#gmail.com',
password: '$2.',
avatar: '',
verificationCode: '',
passwordResetCode: '',
verified: true,
isAdmin: true,
createdAt: 2022-02-17T16:49:40.000Z,
updatedAt: 2022-02-17T16:49:40.000Z
},
_previousDataValues: {
user_id: '20b42b70-f777-420b-b15b-cbf3732c1a9b',
firstName: 'leo',
lastName: 'qal',
email: 't#gmail.com',
password: '$2.',
avatar: '',
verificationCode: '',
passwordResetCode: '',
verified: true,
isAdmin: true,
createdAt: 2022-02-17T16:49:40.000Z,
updatedAt: 2022-02-17T16:49:40.000Z
},
uniqno: 1,
_changed: Set(0) {},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [
'user_id',
'firstName',
'lastName',
'email',
'password',
'avatar',
'verificationCode',
'passwordResetCode',
'verified',
'isAdmin',
'createdAt',
'updatedAt'
]
},
isNewRecord: false
}
Associations
UserModel.hasOne(CartModel, {
sourceKey: 'user_id',
foreignKey: 'user_id',
as: 'users',
});
CartModel.belongsTo(UserModel, {
foreignKey: 'cart_id',
as: 'carts',
});
//OneToMany Association
UserModel.hasMany(SessionModel, {
sourceKey: 'user_id',
foreignKey: 'user_id',
as: 'sessions', // this determines the name in `associations`!
});
CategoryModel.hasMany(ProductModel, {
sourceKey: 'category_id',
foreignKey: 'category_id',
as: 'products',
});

Sequelize create return id: undefined

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
}

Updating instance with multiple associations in Sequelize

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

How to pass the output of a Sequelize query to another function that will return a JSON object with express?

so I am building a Restful API with nodeJS , Postgres plus sequelize and express as main dependencies.
I'm adding a layer that will pull all orders data from the database upon a /get request on my api. I have 2 main files to get the job done plus a router which I think is irrelevant in this problem so I won't include it :
// services/orders.js
import { Order } from '../models'
const test = () => {
Order.findAll().then(data => {
console.log(data)
})
};
This seems to works fine since it console out a array that contain the list of items I did input manually into the database. It looks like the following :
[ order {
dataValues:
{ id: 0,
title: 'blue orange',
date: 2018-11-14T05:20:11.735Z,
user_id: '8753iuufsd98',
createdat: 2018-11-14T05:20:16.831Z,
updatedat: 2018-11-14T05:20:20.072Z },
_previousDataValues:
{ id: 0,
title: 'blue orange',
date: 2018-11-14T05:20:11.735Z,
user_id: '8753iuufsd98',
createdat: 2018-11-14T05:20:16.831Z,
updatedat: 2018-11-14T05:20:20.072Z },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: 'us',
schemaDelimiter: '',
defaultScope: {},
scopes: [],
indexes: [],
name: [Object],
omitNull: false,
createdAt: 'createdat',
updatedAt: 'updatedat',
sequelize: [Object],
hooks: {},
uniqueKeys: {} },
_options:
{ isNewRecord: false,
_schema: 'us',
_schemaDelimiter: '',
raw: true,
attributes: [Array] },
__eagerlyLoadedAssociations: [],
isNewRecord: false },
order {
dataValues:
{ id: 1,
title: 'black blue',
date: 2018-11-14T07:47:09.743Z,
user_id: 'lksdfjsldjfl',
createdat: 2018-11-14T07:47:12.698Z,
updatedat: 2018-11-14T07:47:15.097Z },
_previousDataValues:
{ id: 1,
title: 'black blue',
date: 2018-11-14T07:47:09.743Z,
user_id: 'lksdfjsldjfl',
createdat: 2018-11-14T07:47:12.698Z,
updatedat: 2018-11-14T07:47:15.097Z },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: 'us',
schemaDelimiter: '',
defaultScope: {},
scopes: [],
indexes: [],
name: [Object],
omitNull: false,
createdAt: 'createdat',
updatedAt: 'updatedat',
sequelize: [Object],
hooks: {},
uniqueKeys: {} },
_options:
{ isNewRecord: false,
_schema: 'us',
_schemaDelimiter: '',
raw: true,
attributes: [Array] },
__eagerlyLoadedAssociations: [],
isNewRecord: false },
order {
dataValues:
{ id: 2,
title: 'ornage yellow',
date: 2018-11-14T07:47:31.768Z,
user_id: 'hfjkseiurr',
createdat: 2018-11-14T07:47:34.337Z,
updatedat: 2018-11-14T07:47:36.626Z },
_previousDataValues:
{ id: 2,
title: 'ornage yellow',
date: 2018-11-14T07:47:31.768Z,
user_id: 'hfjkseiurr',
createdat: 2018-11-14T07:47:34.337Z,
updatedat: 2018-11-14T07:47:36.626Z },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: 'us',
schemaDelimiter: '',
defaultScope: {},
scopes: [],
indexes: [],
name: [Object],
omitNull: false,
createdAt: 'createdat',
updatedAt: 'updatedat',
sequelize: [Object],
hooks: {},
uniqueKeys: {} },
_options:
{ isNewRecord: false,
_schema: 'us',
_schemaDelimiter: '',
raw: true,
attributes: [Array] },
__eagerlyLoadedAssociations: [],
isNewRecord: false } ]
Now , I have a controller with a function getOrders that look like the following and is suppose to return the JSON object outputted by services/orders.js :
// controllers/orders.js
function getOrders(req, res) {
return res.send({
data : orderServices.test()
})
}
The problem here is that upon get request with postman , controllers/orders.js return this :
//output on postman ...
{}
an empty object .... My question here is how to get the data that have been c-out properly by services/orders.js to controllers/orders.js so express can display it through res.send() and also, why the result of the query don't just stop at :
{ id: 0,
title: 'blue orange',
date: 2018-11-14T05:20:11.735Z,
user_id: '8753iuufsd98',
createdat: 2018-11-14T05:20:16.831Z,
updatedat: 2018-11-14T05:20:20.072Z },
instead of having this long array ?
Sorry if my question is long. I tried to make as simple and not confusing as possible.
I can't answer your last question about the format of your data because I'm unfamiliar with Sequelize, but the trouble you're having passing the data to your ExpressJS response stems from a lack of understanding of the Promise pattern. Have your service function return the Promise instead:
// services/orders.js
import { Order } from '../models'
const test = () => Order.findAll();
// export test at some point
And then call the service function inside your controller to access the returned data:
// controllers/orders.js
function getOrders(req, res) {
orderServices.test()
.then(data => res.send({ data }));
}
Look into asynchronous programming patterns- callbacks first, then Promises- and the reasoning behind why you must take this approach will become clear.
This answer should cover a considerable amount of the relevant subject matter.

Resources