node js nested loop results finally push to single array - node.js

i will get the Array of Answers
but how to get the Answered users info;
the flow is Get List of Posts, Post User Info, Post User Followers Count, Post Likes Count, Login User Liked The Post True or False,
Answers, Answered User Info and Answered User Followers Count
exports.GetPostList = function(req, res) {
var SkipCoun = 0;
SkipCoun = parseInt(req.params.Limit) * 10;
QuestionsPostModel.QuestionsPostType.find({}, {} , {sort:{createdAt : -1}, skip: SkipCoun, limit: 10 }, function(err, result) {
if(err) {
res.status(500).send({status:"False", message: "Some error occurred while Find Following Users ."});
} else {
const GetUserData = (result) =>
Promise.all(
result.map(info => getPostInfo(info))
).then(
results => {
let [UserInfo, UserFollowers, PostRatingCount, UserRatedCount, AnswersCount, AswersArray ] =
results.reduce(([allOne, allTwo, allThree, allFour, allFive, allSix ], [one, two, three, four, five, six]) =>
[allOne.concat([one]), allTwo.concat([two]), allThree.concat([three]), allFour.concat([four]), allFive.concat([five]), allSix.concat([six])], [ [], [], [], [], [], [] ]);
res.send({ status: "True", UserInfo: UserInfo, UserFollowers: UserFollowers, PostRatingCount: PostRatingCount, UserRatedCount: UserRatedCount, AnswersCount:AnswersCount, AswersArray:AswersArray })
}
).catch(err => res.send({ status: "Fale",Error: err}) );
const getPostInfo = info =>
Promise.all([
UserModel.UserType.findOne({'_id': info.UserId }, usersProjection).exec(),
FollowModel.FollowUserType.count({'UserId': info.UserId}).exec(),
RatingModel.QuestionsRating.count({'PostId': info._id , 'ActiveStates':'Active' }).exec(),
RatingModel.QuestionsRating.count({'UserId': req.params.UserId, 'PostId': info._id, 'PostUserId': info.UserId, 'ActiveStates':'Active'}).exec(),
AnswerModel.QuestionsAnwer.count({'PostId': info._id , 'ActiveStates':'Active' }).exec(),
AnswerModel.QuestionsAnwer.find({ 'PostId':info._id }, 'AnswerText UserId Date' ).exec()
]);
GetUserData(result);
}
});
};
How to Get The Result

as you formed the array, and you are passing it inside Promise.all() .
and you just need the data.
Promise.all() docs.
see Below Code (we can just do as promise .then() and .catch()):
exports.GetPostList = function (req, res) {
var SkipCoun = 0;
SkipCoun = parseInt(req.params.Limit) * 10;
QuestionsPostModel.QuestionsPostType.find({}, {}, { sort: { createdAt: -1 }, skip: SkipCoun, limit: 10 }, function (err, result) {
if (err) {
res.status(500).send({ status: "False", message: "Some error occurred while Find Following Users ." });
} else {
const GetUserData = (result) =>
Promise.all(
result.map(info => getPostInfo(info))
).then(
results => {
let [UserInfo, UserFollowers, PostRatingCount, UserRatedCount, AnswersCount, AswersArray] =
results.reduce(([allOne, allTwo, allThree, allFour, allFive, allSix], [one, two, three, four, five, six]) =>
[allOne.concat([one]), allTwo.concat([two]), allThree.concat([three]), allFour.concat([four]), allFive.concat([five]), allSix.concat([six])], [[], [], [], [], [], []]);
res.send({ status: "True", UserInfo: UserInfo, UserFollowers: UserFollowers, PostRatingCount: PostRatingCount, UserRatedCount: UserRatedCount, AnswersCount: AnswersCount, AswersArray: AswersArray })
}
).catch(err => res.send({ status: "Fale", Error: err }));
const getPostInfo = info =>
Promise.all([
UserModel.UserType.findOne({ '_id': info.UserId }, usersProjection).exec(),
FollowModel.FollowUserType.count({ 'UserId': info.UserId }).exec(),
RatingModel.QuestionsRating.count({ 'PostId': info._id, 'ActiveStates': 'Active' }).exec(),
RatingModel.QuestionsRating.count({ 'UserId': req.params.UserId, 'PostId': info._id, 'PostUserId': info.UserId, 'ActiveStates': 'Active' }).exec(),
AnswerModel.QuestionsAnwer.count({ 'PostId': info._id, 'ActiveStates': 'Active' }).exec(),
AnswerModel.QuestionsAnwer.find({ 'PostId': info._id }, 'AnswerText UserId Date').exec()
]).then(data => {
let userData = data[0];
let followCount = data[1];
let ratingCount = data[2];
let ratingCountBy_postId = data[3];
let answerCount = data[4];
let answers = data[5];
// now you may need to construct some object or something and pass data as you required.
let result = {
user: userData,
follow_count: followCount,
rating_count: ratingCount,
rating_countBy_postId: ratingCountBy_postId,
answer_count: answerCount,
answers: answers
};
}).catch(error => {
console.log(error)
})
GetUserData(result);
}
});
};

exports.GetPostList = function (req, res) {
var SkipCoun = 0;
SkipCoun = parseInt(req.params.Limit) * 10;
QuestionsPostModel.QuestionsPostType.find({}, {}, { sort: { createdAt: -1 }, skip: SkipCoun, limit: 10 }, function (err, result) {
if (err) {
res.status(500).send({ status: "False", message: "Some error occurred while Find Following Users ." });
} else {
const GetUserData = (result) =>
Promise.all(
result.map(info => getPostInfo(info))
).then( result =>{ console.log(result); res.send({ status: "True", data: result }) }
).catch(err => res.send({ status: "False", Error: err }));
const getPostInfo = info =>
Promise.all([
UserModel.UserType.findOne({ '_id': info.UserId }, usersProjection).exec(),
FollowModel.FollowUserType.count({ 'UserId': info.UserId }).exec(),
RatingModel.QuestionsRating.count({ 'PostId': info._id, 'ActiveStates': 'Active' }).exec(),
RatingModel.QuestionsRating.count({ 'UserId': req.params.UserId, 'PostId': info._id, 'PostUserId': info.UserId, 'ActiveStates': 'Active' }).exec(),
AnswerModel.QuestionsAnwer.count({ 'PostId': info._id, 'ActiveStates': 'Active' }).exec(),
AnswerModel.QuestionsAnwer.find({ 'PostId': info._id }, 'AnswerText UserId Date').exec()
]).then(data => {
let UserData = data[0];
let followCount = data[1];
let ratingCount = data[2];
let UserRating = data[3];
let AnswerCount = data[4];
let Answerdata = data[5];
var AnswersArray= new Array();
return GetAnsUserData();
async function GetAnsUserData(){
for (let ansInfo of Answerdata) {
await getAnswerInfo(ansInfo);
}
let result = {
_id: info._id,
UserId: UserData._id,
UserName: UserData.UserName,
UserCategoryId: UserData.UserCategoryId,
UserCategoryName: UserData.UserCategoryName,
UserImage: UserData.UserImage,
UserCompany: UserData.UserCompany,
UserProfession: UserData.UserProfession,
Followers:followCount,
PostTopicId: info.PostTopicId,
PostTopicName: info.PostTopicName,
PostDate: info.PostDate,
PostText: info.PostText ,
PostLink: info.PostLink,
PostImage: info.PostImage,
PostVideo: info.PostVideo,
RatingCount: ratingCount,
UserRating: UserRating,
AnswersCount: AnswerCount,
Answers: AnswersArray,
};
return result;
}
function getAnswerInfo(ansInfo){
return new Promise(( resolve, reject )=>{
UserModel.UserType.findOne({'_id': ansInfo.UserId }, usersProjection, function(err, AnsUserData) {
if(err) {
res.send({status:"Fale", Error:err });
reject(err);
} else {
FollowModel.FollowUserType.count({'UserId': AnsUserData._id}, function(newerr, count) {
if(newerr){
res.send({status:"Fale", Error:newerr });
reject(newerr);
}else{
var newArray = [];
newArray.push( {
_id: ansInfo._id,
UserId: AnsUserData._id,
UserName: AnsUserData.UserName,
UserCategoryId: AnsUserData.UserCategoryId,
UserCategoryName: AnsUserData.UserCategoryName,
UserImage: AnsUserData.UserImage,
UserCompany: AnsUserData.UserCompany,
UserProfession: AnsUserData.UserProfession,
Followers: count,
Date: ansInfo.Date,
PostId: ansInfo.PostId,
PostUserId: ansInfo.PostUserId ,
AnswerText: ansInfo.AnswerText
}
);
AnswersArray.push(newArray[0]);
resolve(newArray[0]);
}
});
}
});
});
}
}).catch(error => {
console.log(error)
})
GetUserData(result);
}
});
};
Finally I get The Answer
Thanks To ALL

Related

How do I test a sequelize database updating function like this?

Hi I can I test a function like this? I cannot test it properly because it says that relation "facilities" does not exist, however I now it exists because I can add a new record.
I should I test this code:
export async function postMemberController(req, res) {
try {
if (req.decodedToken.user_id || req.decodedToken.id) {
const facility = await db.facility.findOne({
where: { id: req.body.facility_id },
raw: true,
});
if (!facility?.id) {
res.send(
"no facilities"
);
} else {
let member = await db.member.findOne({
where: { id_no: Number(req.body.id_no) },
raw: true,
});
const admin = await db.user.findOne({
where: { facility_id: req.body.facility_id },
raw: true,
});
const data = await db.sequelize.transaction(async t => {
if (member?.id_no) {
await db.member
.update(
{
...req.body,
facility_id: [...new Set([...member.facility_id, req.body.facility_id])],
},
{ where: { id_no: member.id_no } },
{ transaction: t }
)
.catch(e => console.log('error : creation MEMBER??? ', e));
const adminToken = await tokenCreator({ ...admin }, 3);
!req.body?.from &&
(await axios
.put(
`${process.env.CENTRAL_URL}/members`,
{
body: {
...req.body,
facility_id: [...new Set([...member.facility_id, req.body.facility_id])],
from: 'web',
},
where: { id: member.id },
},
{
headers: { authorization: 'Bearer ' + adminToken },
}
)
.catch(e => console.log('erorr ', e.response.data, e.config.url)));
} else {
const auth = adminFirebase.auth;
const firebaseToken = await auth.createCustomToken(generateUUID());
member = await db.member
.create(
{
...req.body,
firebase_token: firebaseToken,
facility_id: [req.body.facility_id],
creator: admin.user_id,
updater: admin.user_id,
},
{ transaction: t }
)
.catch(e => console.log('error : creation MEMBER??? ', e));
if (member) {
const card = await db.card.findOne({
where: { card_id: member.dataValues.card_id },
raw: true,
});
if (card) {
await db.card.update(
{ card_number: req.body.card_number },
{
where: {
card_id: member.dataValues ? member.dataValues.card_id : member.card_id,
},
},
{ transaction: t }
);
} else {
const newCard = await db.card.create(
{
card_number: req.body?.card_number,
card_id: member?.dataValues?.card_id,
creator: admin.user_id,
updater: admin.user_id,
facility_id: req.body.facility_id,
credits: 0,
},
{ transaction: t }
);
}
}
const adminToken = await tokenCreator({ ...admin }, 3);
!req.body?.from &&
(await axios
.post(
`${process.env.CENTRAL_URL}/members`,
{
...req.body,
id: member.dataValues.id,
card_id: member.dataValues ? member.dataValues.card_id : member.card_id,
facility_id: req.body.facility_id,
from: 'web',
},
{
headers: { authorization: 'Bearer ' + adminToken },
}
)
.catch(e => console.log('erorr ', e, e?.response?.data, e.config.url)));
!req.body?.from &&
(await axios
.put(
`${process.env.CENTRAL_URL}/cards`,
{
body: {
card_number: req.body.card_number.toString(),
facility_id: req.body.facility_id,
from: 'web',
},
where: {
card_id: member.dataValues ? member.dataValues.card_id : member.card_id,
},
},
{
headers: { authorization: 'Bearer ' + adminToken },
}
)
.catch(e => console.log('erorr ', e.response.data, e.config.url)));
}
return member;
});
delete data.dataValues?.password;
delete data?.password;
const memberToken = await tokenCreator({ ...data.dataValues }, 3);
return res
.status(200)
.json({ data, session_id: data.id_no || data.dataValues.id_no, token: memberToken });
}
} else {
return res.sendStatus(401);
}
} catch (error) {
res.status(500).send(error.message);
}
}
this is how I try to test it:
it('post member from web terminal', async () => {
try {
jest.mock('../db/models/index.js', () => {
const SequelizeMock = require('sequelize-mock');
const dbMock = new SequelizeMock();
const facility = dbMock.define('facilities', {
id: '6-30189',
})
const member = dbMock.define('members', {});
const card = dbMock.card('cards', {});
});
const req = {
decodedToken: { user_id: makeId() },
body: member,
};
const res = {
sendStatus(num) {},
status(num) {
return { json(payload) {}, send(payload) {} };
},
};
const request = await postMemberController(req, res);
delete member.from;
expect(request).toHaveBeenCalledWith({ ...member });
} catch (error) {
console.log('ERROR post member ', error);
throw new Error(error);
}
});
How do I write a test for this???? when I call postMemberController inside jest it seems that can't find the relations in the table, I tried to console.log db.facility object from jest test output, there is nothing, not even empty object or null or undefined. I don't understand why? How can I solve this??
Here is the object I am sending:
const card_number = 11111111111111;
const card_id = makeId();
const schedule = makeId();
const club = makeId();
const trainer = makeId();
const user = makeId();
const facility_id = '6-30189';
const member = {
from: 'central',
card_number: card_number,
id: makeId(),
first_name: 'Demo',
last_name: 'Demo',
id_no: card_number,
card_id,
home_phone: null,
urgent_phone: null,
email: null,
registered: true,
schedule,
club,
trainer,
birthplace: 'Gölbaşı/Ankara',
birthdate: new Date().toISOString(),
father_name: null,
mother_name: null,
gender: null,
profession: null,
address: null,
phone_number: null,
hes_code: null,
blood_type: null,
nationality: null,
profile_photo: null,
is_employee: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
firebase_token: null,
file: null,
session_ids: null,
facility_id,
following: null,
creator: user,
updater: user,
};

How to send reply to several users at the same time?

I have a doubt!
I'm creating a robot for Cryptocurrencies, and I need to send orders to each user's account, how would I do that? I'm using async/await but this way it sends one at a time, having a huge delay, I'm using MongoDB and NodeJS, below I'll leave my code to be more exemplified:
exports.index = async (req, res) => {
const { position, price, token, target, stop, emailUserScalpSend } = req.body
if (position && price && token && target && stop) {
console.time()
if (emailUserScalpSend === 'fila#gmail.com') {
const users = await User.find({ isAtived: true, apiKey: { $nin: ["", null] }, apiSecret: { $nin: ["", null] }, email: 'gustavofmariano#gmail.com' })
for await (const user of users) {
const config = await ConfigsUser.findOne({ user: user.id, porcentagem: { $nin: ["", null] }, alavancagem: { $nin: ["", null] } })
try {
if (config) await createOrderScalp(token, position, price, stop, target, user.apiKey, user.apiSecret, config.porcentagem, config.alavancagem)
else continue
} catch (error) {
console.log(error.message + ` ERRO AO ENVIAR SINAL DE SCALP ${user.name}`)
continue
}
}
} else {
var users = await User.find({ isAtived: true, apiKey: { $nin: ["", null] }, apiSecret: { $nin: ["", null] } })
var configs = await ConfigsUser.find({ user: users[0]._id, statusBot: true, porcentagem: { $nin: ["", null] }, alavancagem: { $nin: ["", null] } })
for await (const user of users) {
for await (const config of configs) {
try {
if (config.user.toString() === user.id.toString()) {
if (config) createOrderScalp(token + 'USDT', position, price, stop, target, user.apiKey, user.apiSecret, config.porcentagem, config.alavancagem)
else continue
}
} catch (error) {
console.log(error.message + ` ERRO AO ENVIAR SINAL PARA USUÁRIO ${user.name}`)
continue
}
}
}
console.timeEnd()
return res.status(201).json({ message: 'Sinal enviado com sucesso!' })
}
}
else return res.status(404).json({ message: 'Enviar todos os dados necessários!' })
}
How would you go about improving performance?
I thank everyone!

API Only sends 1 chunk of metadata when called

I have a problem with my API that sends metadata when called from my smart contract of website. Its NFT tokens and my database is postgres and API is node.js
The problem is when I mint 1 NFT metadata works perfect, but if I mint 2 or more it will only ever send 1 chunk of data? So only 1 NFT will mint properly and the rest with no data?
Do I need to set a loop function or delay? Does anyone have any experience with this?
Any help would be much appreciated.
Below is the code from the "controller" folder labeled "nft.js"
const models = require("../../models/index");
const path = require("path");
const fs = require("fs");
module.exports = {
create_nft: async (req, res, next) => {
try {
const dir = path.resolve(__dirname + `../../../data/traitsfinal.json`);
const readCards = fs.readFileSync(dir, "utf8");
const parsed = JSON.parse(readCards);
console.log("ya data ha final ??", parsed);
parsed.forEach(async (item) => {
// return res.json(item)
let newNft = await models.NFT.create({
name: item.Name,
description: item.Description,
background: item.Background,
body: item.Body,
mouth: item.Mouth,
eyes: item.Eyes,
head_gear: item.Head_Gear,
tokenId: item.tokenId,
image: item.imagesIPFS,
});
});
return res.json({
data: "nft created",
error: null,
success: true,
});
} catch (error) {
console.log("server error", error.message);
next(error);
}
},
get_nft: async (req, res, next) => {
try {
const { id } = req.params;
// console.log("id ?????????",id)
// console.log("type of ",typeof(id))
// const n=Number(id)
// console.log("type of ",typeof(id))
const nft = await models.NFT.findByPk(id);
if (!nft) {
throw new Error("Token ID invalid");
}
if (!nft.isMinted) {
throw new Error("Token not minted");
}
console.log(nft);
// }
const resObj = {
name: nft.name,
description: nft.description,
image: `https://gateway.pinata.cloud/ipfs/${nft.image}`,
attributes: [
{ trait_type: "background", value: `${nft.background}` },
{ trait_type: "body", value: `${nft.body}` },
{ trait_type: "mouth", value: `${nft.mouth}` },
{ trait_type: "eyes", value: `${nft.eyes}` },
{ trait_type: "tokenId", value: `${nft.tokenId}` },
{
display_type: "number",
trait_type: "Serial No.",
value: id,
max_value: 1000,
},
],
};
return res.json(resObj);
} catch (error) {
console.log("server error", error.message);
next(error);
}
},
get_nft_all: async (req, res, next) => {
try {
// console.log("id ?????????",id)
// console.log("type of ",typeof(id))
// const n=Number(id)
// console.log("type of ",typeof(id))
const nft = await models.NFT.findAndCountAll({
limit: 10
});
// console.log(nft);
if (!nft) {
throw new Error("Token ID invalid");
}
// if (nft.isMinted) {
// throw new Error("Token not minted");
// }
// console.log(nft);
// }
var resObjarr = [];
for (var i = 0; i < nft.rows.length; i++) {
resObj = {
name: nft.rows[i].name,
description: nft.rows[i].description,
image: `https://gateway.pinata.cloud/ipfs/${nft.rows[i].image}`,
attributes: [
{ trait_type: "background", value: `${nft.rows[i].background}` },
{ trait_type: "body", value: `${nft.rows[i].body}` },
{ trait_type: "mouth", value: `${nft.rows[i].mouth}` },
{ trait_type: "eyes", value: `${nft.rows[i].eyes}` },
{ trait_type: "tokenId", value: `${nft.rows[i].tokenId}` },
{
display_type: "number",
trait_type: "Serial No.",
value: nft.rows[i].id,
max_value: 1000,
},
],
};
resObjarr.push(resObj);
}
console.log(JSON.stringify(resObjarr))
return res.json(resObjarr);
} catch (error) {
console.log("server error", error.message);
next(error);
}
},
mint: async (req, res, next) => {
try {
const { id } = req.params;
const updated = await models.NFT.findByPk(id);
if (!updated) {
throw new Error("NFT ID invalid");
}
if (updated.isMinted) {
throw new Error("NFT Already minted");
}
updated.isMinted = true;
updated.save();
return res.json({
data: "Token minted successfully",
error: null,
success: true,
});
} catch (error) {
console.log("server error", error.message);
next(error);
}
},
};
Below is from the routes folder.
const router = require("express").Router();
const auth=require("../middleware/auth")
const {
create_nft,
get_nft,
get_nft_all,
mint
} = require("../controller/nft");
router.post(
"/create",
create_nft
);
router.get(
"/metadata/:id",
get_nft
);
router.get(
"/metadata",
get_nft_all
);
router.put(
"/mint/:id",
mint
);
module.exports = router;
Looking your code,you may having some kind of asyncrhonous issue in this part:
parsed.forEach(async (item) => {
// return res.json(item)
let newNft = await models.NFT.create({
name: item.Name,
description: item.Description,
background: item.Background,
body: item.Body,
mouth: item.Mouth,
eyes: item.Eyes,
head_gear: item.Head_Gear,
tokenId: item.tokenId,
image: item.imagesIPFS,
});
});
Because .forEach is a function to be used in synchronous context and NFT.create returns a promise (that is async). So things happens out of order.
So one approach is to process the data first and then perform a batch operation using Promise.all.
const data = parsed.map(item => {
return models.NFT.create({
name: item.Name,
description: item.Description,
background: item.Background,
body: item.Body,
mouth: item.Mouth,
eyes: item.Eyes,
head_gear: item.Head_Gear,
tokenId: item.tokenId,
image: item.imagesIPFS,
})
})
const results = await Promise.all(data)
The main difference here is Promise.all resolves the N promises NFT.create in an async context in paralell. But if you are careful about the number of concurrent metadata that data may be too big to process in parallel, then you can use an async iteration provided by bluebird's Promise.map library.
const Promise = require('bluebird')
const data = await Promise.map(parsed, item => {
return models.NFT.create({
name: item.Name,
description: item.Description,
background: item.Background,
body: item.Body,
mouth: item.Mouth,
eyes: item.Eyes,
head_gear: item.Head_Gear,
tokenId: item.tokenId,
image: item.imagesIPFS,
})
})
return data

How to do sorting in nodejs in backend

This is my node Api
router.post("/*****", async function(req, res, err) {
let limit = 5;
let offset = 0;
tblAdmin
.findAndCountAll()
.then(data => {
console.log("hello world", req.body);
let page = (req.body.page && req.body.page) || 1;
let sortfield = req.body.sortfield;
let sortOrder = req.body.sortOrder;
let pages = Math.ceil(data.count / limit);
offset = limit * (page - 1);
tblAdmin
.findAll({
attributes: ["id", "firstName", "lastName", "status", "email"],
limit: limit,
offset: offset
// order: [`firstName`, `DESC`]
// $sort: { id: 1 }
})
.then(users => {
res.status(200).json({
status: 1,
message: "Data has been retrieved",
result: users,
count: data.count,
pages: pages
});
});
// res.status(200).json({
// status: 1,
// message: "Data has been retrieved",
// data: data.map(result => {
// return {
// id: result.id,
// firstName: result.firstName,
// lastName: result.lastName,
// status: result.status,
// email: result.email
// };
// })
// });
})
.catch(err => {
res.status(500).json({
status: 0,
message: "Data is not retrieved from database"
});
});
});
and this is my react front end
axios.post(`http://abc/**`, params).then(res => {
const pagination = { ...this.state.pagination };
let apiData = res.data.result;
console.log("Data", apiData);
console.log("params", params);
if (res.data.status === 1) {
const objects = apiData.map(row => ({
key: row.id,
id: row.id,
firstName: row.firstName,
lastName: row.lastName,
status: row.status,
email: row.email
}));
console.log(res.data);
pagination.total = res.data.count;
this.setState({
loading: false,
data: objects,
pagination
});
} else {
console.log("Database status is not 1!");
}
});
now this is shown on a table and when i select the field of table in front end it should show ascending or descending order i need to do that order in backend.
from front end i m sending param which includes pagination, sortfield and sortorder and i m getting that in backend now what should i do to change the table according to my order?
The document can be found here
router.post("/*****", async function(req, res, err) {
let limit = 5;
let offset = 0;
tblAdmin
.findAndCountAll()
.then(data => {
console.log("hello world", req.body);
let page = (req.body.page && req.body.page) || 1;
let sortfield = req.body.sortfield;
let sortOrder = req.body.sortOrder;
let pages = Math.ceil(data.count / limit);
offset = limit * (page - 1);
tblAdmin
.findAll({
attributes: ["id", "firstName", "lastName", "status", "email"],
limit: limit,
offset: offset
order: [[sortfield || 'id', sortOrder || 'DESC']] // fixed at here
})
.then(users => {
res.status(200).json({
status: 1,
message: "Data has been retrieved",
result: users,
count: data.count,
pages: pages
});
});
})
.catch(err => {
res.status(500).json({
status: 0,
message: "Data is not retrieved from database"
});
});
});
Edit 1: Add sort default if sortfield or sortOrder is undefined

NoedJS forEach with add new element on a http-request

how to add new element in an array with a http request.
I have a code like this but it doesn't add new element because of async on nodejs and I don't know how can I pass it.
arr = [
{ id: 123},
{ id: 124},
{ id: 125},
{ id: 126},
]
arr.forEach(function(row, index) {
request.post('/test')
.then((data) => {
row.status = "success"
})
.catch((error) => {
row.status = "failed"
});
});
so that i can achieve something like this.
[
{ id: 123, status: 'success' },
{ id: 124, status: 'failed' },
{ id: 125, status: 'failed' },
{ id: 126, status: 'success' },
]
I'm new in NodeJs. thank you guys
You have to use Promise.all because you're handling several promises:
let arr = [
{ id: 123},
{ id: 124},
{ id: 125},
{ id: 126}
]
Promise.all(arr.map((row, index) => {
return request.post('/test')
.then(data => {
row.status = "success"
})
.catch(error => {
row.status = "failed"
});
})).then(() => console.log(arr))
You can try this popular node module Async. Try this .each here http://caolan.github.io/async/docs.html#each.
async.each(arr, _your_function, (err) => {
// check success
})
_your_function(){}
use async.eachOf, you can access element and index in the array.
var async = require("async");
var arr = [
{ id: 123},
{ id: 124},
{ id: 125},
{ id: 126},
];
async.eachOf(arr, function(e, i, ecb){
request.post('/test',)
.then( (data) => {
e.status = "success"
return ecb(null);
})
.catch( (error) => {
e.status = "failed"
return ecb(null);
});
}, function(err){
if(err)
{
console.log("err");
}
else
{
console.log(arr);
}
});

Resources