GraphQL error update mutation "Resolve function for \"User.id\" returned undefined" - undefined

I am a newbie to GraphQL and trying to write an update mutation. However, I am receiving Resolve function for \"User.id\" returned undefined" error although the database is actually got updated.
What am I doing wrong?
userSchema.js:
import Sequelize from 'sequelize';
import SqlHelper from '../helpers/sqlhelper';
const config = require('../../config');
const sequelizer = new SqlHelper(config).Init();
const createUser = sequelizer.define(
'createUser',
{
...
}
);
const updateUser = sequelizer.define(
'updateUser',
{
id: {
type: Sequelize.UUID,
field: 'Id',
primaryKey: true,
defaultValue: Sequelize.UUIDV4,
},
username: {
type: Sequelize.STRING,
field: 'Username',
allowNull: true,
},
email: {
type: Sequelize.STRING,
field: 'Email',
allowNull: true,
},
firstname: {
type: Sequelize.STRING,
field: 'FirstName',
allowNull: true,
},
lastname: {
type: Sequelize.STRING,
field: 'LastName',
allowNull: true,
},
....
},
{
// define the table's name
tableName: 'Users',
},
);
module.exports = User;
UserResolver.js:
import User from '../dbschemas/user';
import Sequelize from 'sequelize';
const Op = Sequelize.Op;
export default {
Mutation: {
createUser: async (obj, args) =>
(await User.create(args)),
updateUser: async (obj, args) =>
(await User.update(args,
{
where: {
id: args.id,
},
returning: true
}))
}
};
Although calling updateUser from GraphiQL updates the records (in db), it results in a "Resolve function for \"User.id\" returned undefined" error:
mutation{
updateUser(id: "2ecd38ca-cf12-4e79-ac93-e922f24af9e3",
username: "newUserTesting",
email: "testemail#yahoo.com",
lastname: "TestUserLName",
firstname: "fname1") {
id
}
}
{
"data": null,
"errors": [
{
"message": "Resolve function for \"User.id\" returned undefined",
"locations": [
{
"line": 16,
"column": 4
}
],
"path": [
"updateUser",
"id"
]
}
]
}

The issue is clear, your resolver does not return an object containing id.
The docs say that Model.update returns an array in which the 2nd element is the affected row.
Hence, your resolver should look like:
async updateUser(obj, args) {
const resultArray = await User.update( ... )
return resultArray[1]
}
... To be replaced by whatever you need.

So apparently, update does NOT return affected rows for MSSQL, only the number of records affected.
This is true only for postgres when returning: true:
public static update(values: Object, options: Object): Promise<Array<affectedCount, affectedRows>>
Setting returning: true (for MSSQL) returns undefined (and order of params in the array is not even in the right order... i.e. first affectedRows -> undefined, then affectedCount ->num of affected rows.)
Tho get an object back you would need to do something like this:
Mutation: {
createUser: async (obj, args) =>
(await User.create(args.user)),
updateUser: async (obj, args, context, info) =>{
let user = args.user;
let response = await User.update(user,
{
where: {
[Op.or]: [{ email: user.email }, { id: user.id }, { username: user.username }, { lastname: user.lastname}]
},
//returning: true //not working... only for postgres db :(
}).then(ret => {
console.log('ret', ret);
return ret[0];
}).catch(error => {
console.log('error', error)
});
if (response > 0) return user; //return record
//return response > 0; //return true
}
}

Related

I'm trying to join 3 tables in node.js using sequelize but having trouble. What is the problem with my code?

Newer to Node.js any advice would be appreciated! Trying to join 3 tables with a common key but getting the error...
react_devtools_backend.js:4026 [GraphQL error]: Message: Unknown column 'google_responsive_descriptions.googleTextAdId' in 'on clause', Location: [object Object], Path: listGoogleTextAds
googleResponsiveAds.js file
module.exports = (sequelize, DataTypes) => {
const googleResponsiveAds = sequelize.define(
"google_responsive_headlines",
{
responsive_headlines: { type: DataTypes.STRING },
responsive_path_1: { type: DataTypes.STRING },
responsive_path_2: { type: DataTypes.STRING }
},
{
timestamps: false,
tableName: "google_responsive_headlines"
}
);
//googleResponsiveAds.associate = () => {};
googleResponsiveAds.associate = function (models) {
googleResponsiveAds.belongsTo(models.google_text_ads, { foreignKey: "ad_id" });
}
return googleResponsiveAds;
};
googleResponsiveDescriptionsAds.js file
module.exports = (sequelize, DataTypes) => {
const googleResponsiveDescriptionsAds = sequelize.define(
"google_responsive_descriptions",
{
responsive_descriptions: { type: DataTypes.STRING }
},
{
timestamps: false,
tableName: "google_responsive_descriptions"
}
);
//googleResponsiveDescriptionsAds.associate = () => {};
googleResponsiveDescriptionsAds.associate = function (models) {
googleResponsiveDescriptionsAds.belongsTo(models.google_text_ads, { foreignKey: "ad_id" });
}
return googleResponsiveDescriptionsAds;
};
googleTextAds.js file
module.exports = (sequelize, DataTypes) => {
const googleTextAds = sequelize.define(
"google_text_ads",
{
headline_pt_1: { type: DataTypes.STRING },
headline_pt_2: { type: DataTypes.STRING },
headline_pt_3: { type: DataTypes.STRING },
final_url: { type: DataTypes.STRING },
display_url: { type: DataTypes.STRING },
status: { type: DataTypes.STRING },
type: { type: DataTypes.STRING },
description1: { type: DataTypes.STRING },
description2: { type: DataTypes.STRING },
path1: { type: DataTypes.STRING },
path2: { type: DataTypes.STRING },
ad_id: { type: DataTypes.INTEGER }
},
{
timestamps: false,
tableName: "google_text_ads"
}
);
//googleTextAds.associate = () => {};
googleTextAds.associate = function (models) {
googleTextAds.hasMany(models.google_responsive_headlines, { sourceKey: 'ad_id' })
googleTextAds.hasMany(models.google_responsive_descriptions, { sourceKey: 'ad_id' });
};
return googleTextAds;
};
Here is the section of the queries/google.js
{
key: "listGoogleTextAds",
prototype:
"(customer_id: Int, start_date: String, end_date: String): [GoogleTextAds]",
run: async args => {
const allIds = await google_text_ads
.findAll({
attributes: [
"ad_id",
"date",
"impressions",
"clicks",
"cost"
],
include: [
{
model: google_responsive_descriptions,
as: 'google_responsive_descriptions',
required: true,
attributes: [
"ad_id",
"responsive_descriptions"
],
},
{
model: google_responsive_headlines,
as: 'google_responsive_headlines',
attributes: [
"ad_id",
"responsive_headlines",
"responsive_path_1",
"responsive_path_2"
]
}
],
where: {
customer_id: args.customer_id,
date: {
[Op.gte]: args.start_date,
[Op.lte]: args.end_date
},
status: {
[Op.in]: ["ENABLED"]
},
type: {
[Op.in]: ["EXPANDED_TEXT_AD", "RESPONSIVE_SEARCH_AD"]
}
}
})
}
}
EDIT: Here's my query
export const LIST_GOOGLE_TEXT_ADS = gql`
query listGoogleTextAds(
$customer_id: Int!
$start_date: String!
$end_date: String!
) {
listGoogleTextAds(
customer_id: $customer_id
start_date: $start_date
end_date: $end_date
) {
ad_id
type
headline_pt_1
headline_pt_2
headline_pt_3
description1
description2
path1
path2
status
final_url
display_url
impressions
clicks
cost
}
}
`;
and my models...
type GoogleTextAds {
ad_id: Int
type: String
headline_pt_1: String
headline_pt_2: String
headline_pt_3: String
description1: String
description2: String
path1: String
path2: String
final_url: String
display_url: String
status: String
impressions: Int
clicks: Int
cost: Float
}
type GoogleResponsiveAds{
ad_id: Int
responsive_headlines: String
responsive_path_1: String
responsive_path_2: String
}
type GoogleResponsiveDescriptionsAds{
ad_id: Int
responsive_descriptions: String
}
here is the query I am trying to replicate...
SELECT distinct google_responsive_headlines.responsive_headlines,
google_responsive_headlines.responsive_path_1,
google_responsive_headlines.responsive_path_2,
google_responsive_descriptions.responsive_descriptions,
google_text_ads.date,
google_text_ads.clicks,
google_text_ads.cost,
google_text_ads.impressions,
google_text_ads.ad_id,
google_text_ads.status,
google_text_ads.final_url,
google_text_ads.create_time
FROM irene_db.google_text_ads
inner JOIN irene_db.google_responsive_headlines ON google_responsive_headlines.ad_id = google_text_ads.ad_id
inner JOIN irene_db.google_responsive_descriptions ON google_responsive_descriptions.ad_id = google_text_ads.ad_id
where google_text_ads.customer_id = 144 and google_text_ads.date = '2022-06-09' and
google_responsive_headlines.customer_id = 144 and google_responsive_headlines.date = '2022-06-09' and
google_responsive_descriptions.customer_id = 144 and google_responsive_descriptions.date = '2022-06-09';
EDIT2: Where associate gets called...
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const dotenv = require("dotenv");
dotenv.config();
const basename = path.basename(module.filename);
const db = {};
let sequelize;
const { DB_HOST, DB_USER, DB_PASS, DB_NAME } = process.env;
sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASS, {
dialect: "mysql",
host: DB_HOST
});
fs.readdirSync(__dirname)
.filter(
file =>
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
)
.forEach(file => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
EDIT 3:
After boc4life's code suggestions I'm now at least getting graphql to attempt the query. But it's using the wrong field name in the join on section. Here's the query it built...
SELECT
`google_text_ads`.`id`,
`google_text_ads`.`ad_id`,
`google_text_ads`.`date`,
`google_text_ads`.`impressions`,
`google_text_ads`.`clicks`,
`google_text_ads`.`cost`,
`google_responsive_descriptions`.`id` AS `google_responsive_descriptions.id`,
`google_responsive_descriptions`.`responsive_descriptions` AS `google_responsive_descriptions.responsive_descriptions`,
`google_responsive_headlines`.`id` AS `google_responsive_headlines.id`,
`google_responsive_headlines`.`responsive_headlines` AS `google_responsive_headlines.responsive_headlines`,
`google_responsive_headlines`.`responsive_path_1` AS `google_responsive_headlines.responsive_path_1`,
`google_responsive_headlines`.`responsive_path_2` AS `google_responsive_headlines.responsive_path_2`
FROM
`google_text_ads` AS `google_text_ads`
INNER JOIN
`google_responsive_descriptions` AS `google_responsive_descriptions` ON `google_text_ads`.`ad_id` = `google_responsive_descriptions`.`googleTextAdId`
INNER JOIN
`google_responsive_headlines` AS `google_responsive_headlines` ON `google_text_ads`.`ad_id` = `google_responsive_headlines`.`googleTextAdId`
WHERE
`google_text_ads`.`customer_id` = 142
AND (`google_text_ads`.`date` >= '2022-05-17'
AND `google_text_ads`.`date` <= '2022-06-17')
AND `google_text_ads`.`status` IN ('ENABLED')
AND `google_text_ads`.`type` IN ('EXPANDED_TEXT_AD' , 'RESPONSIVE_SEARCH_AD');
Try using the tableName defined while defining the table structure to access the model while creating associations.
Example: instead of
models.googleTextAds
do
models.google_text_ads
What jumps out to me is all of those nested includes. Since you are joining the Headlines and Descriptions tables on the Text_Ads table, I believe all you should need here is the one include array containing two objects, one for Headlines and one for Descriptions.
Currently you have Headlines nested under Descriptions, which won't work because Descriptions does not have an association with Headlines directly defined. You also have an include of Text_Ads nested inside of Descriptions, which should WORK, but should be unnecessary since that is the model you are calling findAll() on. You can bring the Text_Ads attributes you are querying for out into that parent object as a sibling of include. Something like this looks like a good starting point for getting the query cleaned up. I have also removed a bunch of the unnecessary sequelize.col() that you had in your initial post.
const allIds = await google_text_ads
.findAll({
attributes: [
"ad_id",
[sequelize.fn("max", sequelize.col("date")), "date"],
[sequelize.fn("sum", sequelize.col("impressions")), "impressions"],
[sequelize.fn("sum", sequelize.col("clicks")), "clicks"],
[sequelize.fn("sum", sequelize.col("cost")), "cost"]
],
include: [
{
model: Models.google_responsive_descriptions,
as: 'googleResponsiveDescriptionsAds',
required: true,
attributes: [
"ad_id",
"responsive_descriptions"
],
},
{
model: Models.google_responsive_headlines,
as: 'googleResponsiveAds',
attributes: [
"ad_id",
"responsive_headlines",
"responsive_path_1",
"responsive_path_2"
]
}
],
where: {
customer_id: args.customer_id,
date: {
[Op.gte]: args.start_date,
[Op.lte]: args.end_date
},
status: {
[Op.in]: ["ENABLED"]
},
type: {
[Op.in]: ["EXPANDED_TEXT_AD", "RESPONSIVE_SEARCH_AD"]
}
}
})

Express js - how to remove certain field from response

In my current login api, it returns
"user": {
"id": "3e85decc-2af4-436c-8b7f-e276771234f5",
"email": "cccc#cccc.com",
"password": "$xxxxxxxxxx",
"createdAt": "2021-05-14T08:48:31.000Z",
"updatedAt": "2021-05-14T08:48:31.000Z"
},
"token": "xxxxx"
}
I want to remove the password field in my response, so I use delete user.password in my code, but it's not working
/api/users.js
router.post('/login', (req, res, next) => {
passport.authenticate('local', {session: false}, (err, user, info) =>{
if (err || !user) {...}
req.login(user, {session: false}, (err) => {
if (err) {
res.send(err);
}
const token = jwt.sign(user, 'your_jwt_secret');
console.log(user) // show dataValues and _previousDataValues instead of normal JSON object
delete user.password // not working
return res.json({user, token});
});
})(req, res);
});
I tried to log user object for above file, it returns:
users {
dataValues: {
id: '3e85decc-2af4-436c-8b7f-e276771234f5',
email: 'cccc#cccc.com',
password: '$xxxxxxxxxx',
createdAt: 2021-05-14T08:48:31.000Z,
updatedAt: 2021-05-14T08:48:31.000Z
},
_previousDataValues: {
id: '3e85decc-2af4-436c-8b7f-e276771234f5',
email: 'cccc#cccc.com',
password: '$xxxxxxxxxx',
createdAt: 2021-05-14T08:48:31.000Z,
updatedAt: 2021-05-14T08:48:31.000Z
},
_changed: Set(0) {},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [ 'id', 'email', 'password', 'createdAt', 'updatedAt' ]
},
isNewRecord: false
}
This is my user model. I am using Sequelize.
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
const db = require('../sequelize')
let users = db.define('users', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: 'email'
},
password: {
type: DataTypes.STRING,
},
},
{
hooks: {
beforeCount(options) {
options.raw = false;
}
}
}
);
module.exports = users;
Finally solved it using user.get({plain: true})
let plainUser = user.get({plain: true})
delete plainUser['password']
return res.json({user, token});
It's probably not a good idea to delete properties from the Model directly. Try using ToJSON() to convert the Model to a plain Javascript object and delete the password from that.
plainUser = user.ToJSON();
delete plainUser.password
why dont you re-create your result response, something like this:
let response = {
"user": {
"id": user.dataValues.id,
"email": user.dataValues.email,
"createdAt": user.dataValues.createdAt,
"updatedAt": user.dataValues.updatedAt
},
"token": "xxxxx"
}
JSON.stringify(response)
Try below code in your model to override the sequelize toJSON function
const User = db.define('users', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: 'email'
},
password: {
type: DataTypes.STRING,
},
},
{
hooks: {
beforeCount(options) {
options.raw = false;
}
}
}
);
User.prototype.toJSON = function () {
const values = Object.assign({}, this.get());
delete values.password;
return values;
};
or using omit() withlodash for cleaner code
User.prototype.toJSON = function () {
const values = {
..._.omit(this.get(), ['password'])
};
return values;
};

nodejs - passport.use callback return dataValues and _previousDataValues instead of a normal object

I am using passport.js module for Authentication and Sequelize mysql for database management.
error occurs when authenticating user:
{
"errors": {
"message": "WHERE parameter \"id\" has invalid \"undefined\" value",
"error": {}
}
}
When authenticating the user, console.log(jwtPayload) in file passport.js shows below results.
{
dataValues: {
id: '06c19eb0-995f-45f4-81d7-26ec3b401234',
email: 'CCCC#gmail.com',
createdAt: '2021-05-14T01:51:31.000Z',
updatedAt: '2021-05-14T01:51:31.000Z'
},
_previousDataValues: {
id: '06c19eb0-995f-45f4-81d7-26ec3b401234',
email: 'CCCC#gmail.com',
createdAt: '2021-05-14T01:51:31.000Z',
updatedAt: '2021-05-14T01:51:31.000Z'
},
_changed: {},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [ 'id', 'email', 'createdAt', 'updatedAt' ]
},
isNewRecord: false,
iat: 1620961695
}
instead of
{
id: '06c19eb0-995f-45f4-81d7-26ec3b401234',
email: 'CCCC#gmail.com',
createdAt: '2021-05-14T01:51:31.000Z',
updatedAt: '2021-05-14T01:51:31.000Z'
}
passport.js
var passport = require('passport');
const passportJWT = require("passport-jwt");
const JWTStrategy = passportJWT.Strategy;
var LocalStrategy = require('passport-local').Strategy;
const ExtractJWT = passportJWT.ExtractJwt;
const bcrypt = require('bcryptjs');
var User = require('../models/Users')
module.exports = function(passport) {
passport.use(new JWTStrategy({
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey : 'your_jwt_secret'
},
function (jwtPayload, done) {
console.log(jwtPayload)
return User.findOne({where: {id:jwtPayload.id}})
.then(user => {
return done(null, user);
})
.catch(err => {
return done(err);
});
}
));
};
Sequelize returns dataValues and _previousDataValues properties by design. You can pass the current values with a small modification.
return User.findOne({where: {id:jwtPayload.id}})
.then(user => {
return done(null, user.dataValues);
})

How to update in nodejs using sequelize

I want to update the wallet table when I deposit an amount in the wallet.
My code is like this:
model wallet.js
'use strict';
module.exports = (sequelize, DataTypes) => {
var Model = sequelize.define('wallet', {
id: {
type: DataTypes.INTEGER,
field: 'id',
primaryKey: true,
autoIncrement: true
},
cid: {
type: DataTypes.STRING,
field: 'cid'
},
deposit: {
type: DataTypes.INTEGER,
field: 'deposit'
},
withdrawal: {
type: DataTypes.INTEGER,
field: 'withdrawal'
},
available: {
type: DataTypes.INTEGER,
field: 'available',
},
comments: {
type: DataTypes.DATE,
field: 'comments'
},
online: {
type: DataTypes.STRING,
field: 'online'
}
}, {
tableName: 'wallet',
timestamps: false
});
Model.associate = function (models) {
this.orders = this.hasOne(models.orders, {
as: 'orders',
foreignKey: 'wid'
});
};
Model.prototype.toWeb = function (pw) {
let json = this.toJSON();
return json;
};
return Model;
};
here the wallet deposit is happening here i am using set method to update the wallet
walletcontroller.js
const deposit = async function (req, res) {
res.setHeader('Content-Type', 'application/json');
let err, wallet, existingWallet;
let wallet_info = req.body;
[err, existingWallet] = await to(Wallet.findAll({
limit: 1,
where: {
cid: wallet_info.cid,
},
order: [
['id', 'DESC']
]
}));
[err, wallet] = await to(Wallet.set(wallet_info, {
limit: 1,
where: {
cid: wallet_info.cid,
},
order: [
['id', 'DESC']
]
}));
if (err) return ReE(res, err, 422);
if (existingWallet[0] != 'undefined') {
wallet.available = existingWallet[0].available + wallet_info.deposit;
wallet.comments = new Date();
} else {
wallet.available = wallet_info.deposit;
wallet.comments = new Date();
}
console.log("avalible balance:" + wallet.available);
[err, wallet] = await to(wallet.save());
if (err) return ReE(res, err, 422);
return ReS(res, {
wallet: wallet.toWeb()
}, 201);
}
module.exports.deposit = deposit;
please help me out how to update the wallet... when i am callig api here my err msg looks like this
Executing (default): SELECT `id`, `cid`, `deposit`, `withdrawal`, `available`, `comments`, `online` FROM `wallet` AS `wallet` WHERE `wallet`.`cid` = '33' ORDER BY `wallet`.`id` DESC LIMIT 1;
Error:
Uncaught Error { filename: '\\cl-api-master\\controllers\\WalletController.js',
line: 67,
row: 37,
message: 'Wallet.set is not a function',
type: 'TypeError',
stack: 'TypeError: Wallet.set is not a function\n at deposit (E:\\cl-api-master\\controllers\\WalletController.js:67:37)\n at <anonymous>',
arguments: undefined }
POST /v1/wallet/deposit - - ms - -
For Edition, you can simply use -
data.update = await Wallet.update(
{
available: available,
comments: new Date()
},
{
where: { cid: wallet_info.cid }
}
);
available variable can be set using if else condition afterward running above update query.

Creating Primary and Foreign Key relations in Sequelize

I have 2 models Project model and Task model defined in sequelize as shown below
import { INTEGER, STRING, DATE } from 'sequelize';
import sequelize from '../sequelize';
import Task from './task.model'
const ProjectModel = sequelize.define('project', {
project_id: {
type: INTEGER,
primaryKey: true,
autoIncrement: true
},
phabricator_project_id: {
type: STRING,
allowNull: false
},
name: {
type: STRING
},
description: {
type: STRING
},
start_date: {
type: STRING,
},
end_date: {
type: STRING
}
},
{
timestamps: false
}
);
export default ProjectModel;
and the task model
import { INTEGER, STRING, DATE } from 'sequelize';
import sequelize from '../sequelize';
const TaskModel = sequelize.define('task', {
task_id: {
type: INTEGER,
primaryKey: true,
autoIncrement: true
},
title: {
type: STRING
},
status: {
type: STRING
},
priority: {
type: STRING
},
description: {
type: STRING
},
tool_project_id: {
type: STRING
},
date_modified: {
type: STRING
}
},
{
timestamps: false
}
);
export default TaskModel;
What I want to achieve is to create a relation between tool_project_id in TaskModel and phabricator_project_id in ProjectModel (they are same values only diff column names are given) and write a query for a GET request which outputs the data in form shown below
{ {project1Details,TaskDetails-->{task1, task2, task3},
{project2Details,TaskDetails-->{task4, task5, task6},
{project3Details,TaskDetails-->{task7, task8, task9},
{project4Details,TaskDetails-->{task10, task11, task12} }
All the database design has been done accordingly and another file is called to create all these databases. This is written in typescript and I tried this as a GET method
listByProjects(req, res) {
TaskModel.belongsTo(ProjectModel, { as: 'task' , foreignKey: 'tool_project_id'});
ProjectModel.findAll({
include:[{model:TaskModel}],
where:{status:'open'}
}).then(function(projects) {
res.json(projects);
});
}
Here in this method I define the relation and try to list all 'open' tasks and send them back as response but I am getting the error
Unhandled rejection Error: task is not associated to project!
ANY HELP TO THIS PROBLEM WOULD BE WONDERFULL
The answer to this question is that when creating the table we should create the relation and then create the table such as
Create the relation also the name of the key should be same so as to create relation.
TaskModel.belongsTo(ProjectModel, {foreignKey: 'project_id' });
ProjectModel.hasMany(TaskModel, { foreignKey: 'project_id' });
Then create the table project and then tasks
ProjectModel.sync({ force: false }).then(function () {
console.log('Project table created');
TaskModel.sync({ force: false }).then(function () {
console.log('Task table created');
});
});
then in the API method, you are invoking just include the model which you want to provide to get the required data.
ProjectModel.findAll({
include: [{
model: TimeSheetModel,
where: {
status: "ACTIVE"
},
}],
}).then(function (projects) {
const responseData = {
'status': 1,
'message': 'List successfull.',
'projects': projects,
};
res.json(responseData);
}).catch(error => {
const responseData = {
'status': 1,
'message': error.message,
'projects': [],
};
res.json(responseData);
})
This uses nodemon and sequilize to manage node and relations of the table respectively