Merge array on different key in nodejs - node.js

dailyTask=[ { subject: 'Documentation', owner_id: 1 }, { subject: 'SERVICES', owner_id: 2 } ];
emails=[ { employee_id: 1, email_id: 'abcd#gmail.com' }, { employee_id: 2, email_id: 'abcdef#gmail.com' } ];
merge two arrays on keys owner_id and employee_id and the required result is shown below
output=[ {employee_id:1,owner_id:1,email_id:'abcd#gmail.com',subject:'Documentation'}, {employee_id:2,owner_id:2,email_id:'abcdef#gmail.com',subject:'SERVICES'} ];

You can achieve this using Array.reduce & Object.values
const dailyTasks = [{subject:'Documentation',owner_id:1},{subject:'SERVICES',owner_id:2}];
const emails = [{employee_id:1,email_id:'abcd#gmail.com'},{employee_id:2,email_id:'abcdef#gmail.com'}];
const mergeArrays = (tasks, emails) => {
return Object.values(tasks.reduce((acc,task) => {
//fetch the matching email from the list of emails based on employee_id and owner_id
const matchingEmail = emails.find(({employee_id}) => employee_id === task.owner_id);
//add/update the object with the task & matching email
acc[task.owner_id] = {
...(acc[task.owner_id] || {}),
...task,
...matchingEmail
}
return acc;
}, {}));
}
console.log(mergeArrays(dailyTasks, emails));
.as-console-wrapper {
max-height: 100% !important;
}

Related

Submitting without files resets the all images in the array when making a PATCH request

I'm trying to make a dynamic field for adding team members using Formik.
In my backend, if I do not choose any file and edit only other field such as "memberName" I'm getting message saying;
"Cast to embedded failed for value "{
_id: '63c5687832a80d5d8f717715',
memberName: 'qqaa',
memberJobTitle: 'qq',
memberDescription: 'qq',
images: [ 'undefined' ]
}" (type Object) at path "team" because of "CastError""
I want to keep the existing images if there is no changes in the input field. I'm having this issue for a week and couldn't figure it out.
This is my controller for making a PATCH request;
const updateSection = async (req, res, next) => {
const files = req.files;
const {
pageId,
welcomeTitle,
welcomeDescription,
aboutUsTitle,
aboutUsDescription,
team,
teamTitle,
} = req.body;
let updates = {};
//update other fields if they are provided in the request body
if (welcomeTitle) {
updates.welcomeTitle = welcomeTitle;
}
if (welcomeDescription) {
updates.welcomeDescription = welcomeDescription;
}
if (aboutUsTitle) {
updates.aboutUsTitle = aboutUsTitle;
}
if (aboutUsDescription) {
updates.aboutUsDescription = aboutUsDescription;
}
if (teamTitle) {
updates.teamTitle = teamTitle;
}
if (team) {
let teamPromises = []; //create an empty array to store promises for updating or creating team members
// updates.team.images = [];
team.forEach((item, i) => {
// item -> current team member being processed, i-> index in the array
let teamMember = {
_id: item._id,
memberName: item.memberName,
memberJobTitle: item.memberJobTitle,
memberDescription: item.memberDescription,
images: item.images,
};
if (files && files[i]) {
let file = files[i];
let img = fs.readFileSync(file.path);
let decode_image = img.toString("base64");
teamMember.images = [
{
filename: file.originalname,
contentType: file.mimetype,
imageBase64: decode_image,
},
];
} else {
teamMember.images = item.images;
}
teamPromises.push(
Section.updateOne(
{ pageId: pageId, "team._id": item._id },
{ $set: { "team.$": teamMember } },
{ new: false }
)
);
});
Promise.all(teamPromises)
.then((result) => {
res.status(200).json({ message: "Section updated successfully!" });
})
.catch((error) => {
res.status(500).json({ error: error.message });
});
} else {
//update other fields if no team member provided
Section.findOneAndUpdate({ pageId: pageId }, updates).then(() => {
res.status(200).json({ message: "Section updated successfully!" });
});
}
};

importing a sample excel sheet from database postgresql

I want to import an excel sheet from a database containing state list with a foreign key of countries.
What I want to do is the column for the country to become a dropdown list so that I could enter the state name with the reference country name selected from the country dropdown:
const getStateSampleFile = async (req, res) => {
try {
const countryData = await Countries.findAll({
where: { deleted: false },
});
const workbook = new excelJS.Workbook();
const workSheet = workbook.addWorksheet('StateData');
workSheet.columns = [
// { header: 'S.no', key: 's_no', width: 20 },
{ header: 'Countries', key: 'Countries', width: 20 },
{ header: 'States', key: 'state', width: 20 },
];
// let count = 1;
countryData.forEach((country) => {
// country.s_no = count;
country.Countries = country.name;
// workSheet.addRow(country);
// count += 1;
// return dropList.push({ dlist });
return country.name;
// console.log(dlist,'98989')
// return country.name;
});
// console.log(dlist, '909099090');
workSheet.getCell('A1').dataValidation = {
type: 'list',
allowBlank: true,
formulae: [],
};
workSheet.getRow(1).eachCell((cell) => {
cell.font = { bold: true };
});
const filename = `States${Date.now()}.xlsx`;
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
await workbook.xlsx.writeFile('statesampledata.xlsx');
res.send('done');
return workbook.xlsx.write(res).then(() => {
res.status(200).end();
});
} catch (error) {
throw new Error(error);
}
};

Two if statements to make cmd differentiate between roles

I'm wondering if it is possible to use if statements this way so that the command gives separate messages depending on the users role. This is one attempt I've made but the second if statement is unreachable.
module.exports = {
name: "train",
description: "Train to earn some reputation!",
async execute(client, message, args, cmd, discord, profileData) {
const events1 = [
"sample event",
"sample event",
"sample event",
];
const events2 = [
"sample event",
"sample event",
"sample event",
];
const injuries = [
"sample injury",
"sample injury",
"sample injury",
];
const chosenEvent1 = events1.sort(() => Math.random() - Math.random()).slice(0, 1);
const chosenEvent2 = events2.sort(() => Math.random() - Math.random()).slice(0, 1);
const chosenInjury = injuries.sort(() => Math.random() - Math.random()).slice(0, 1);
const randomNumber1 = Math.floor(Math.random() * 29) + 5;
const randomNumber2 = Math.floor(Math.random() * 9) + 1;
if((!message.member.roles.cache.has('roleid#1'))); {
if(Math.floor(Math.random() * 3) === 0) {
await profileModel.findOneAndUpdate(
{
userID: message.author.id,
},
{
$inc: {
health: -randomNumber2,
},
}
);
return message.channel.send(`${chosenInjury} You lost ${randomNumber2} health and gained no reputation.`);
} else {
await profileModel.findOneAndUpdate(
{
userID: message.author.id,
},
{
$inc: {
reputation: randomNumber1,
},
}
);
return message.channel.send(`${chosenEvent1} You earned ${randomNumber1} reputation!`);
}
if((!message.member.roles.cache.has('roleid#2'))); {
return message.channel.send(`${chosenEvent2} You earned ${randomNumber1} reputation!`);
}
}}
};
So ideally if you have RoleID #1, you have a chance of injury or your reputation increases and you get a message with Event1 prompts. If you have RoleID #2, your reputation just increases and you get a message with Event2 prompts. I hope this is clear.
It seems the brackets are bit off and that is why the code is unreachable.
I have also attached an image of the locations where I made code changes. A key consideration is in javascript try to avoid placing semicolons right after an if statement
Please see the small bracket changes I made in your code example:
module.exports = {
name: 'train',
description: 'Train to earn some reputation!',
async execute(client, message, args, cmd, discord, profileData) {
const events1 = ['sample event', 'sample event', 'sample event'];
const events2 = ['sample event', 'sample event', 'sample event'];
const injuries = ['sample injury', 'sample injury', 'sample injury'];
const chosenEvent1 = events1.sort(() => Math.random() - Math.random()).slice(0, 1);
const chosenEvent2 = events2.sort(() => Math.random() - Math.random()).slice(0, 1);
const chosenInjury = injuries.sort(() => Math.random() - Math.random()).slice(0, 1);
const randomNumber1 = Math.floor(Math.random() * 29) + 5;
const randomNumber2 = Math.floor(Math.random() * 9) + 1;
if (!message.member.roles.cache.has('roleid#1')) {
if (Math.floor(Math.random() * 3) === 0) {
await profileModel.findOneAndUpdate(
{
userID: message.author.id,
},
{
$inc: {
health: -randomNumber2,
},
}
);
return message.channel.send(
`${chosenInjury} You lost ${randomNumber2} health and gained no reputation.`
);
} else {
await profileModel.findOneAndUpdate(
{
userID: message.author.id,
},
{
$inc: {
reputation: randomNumber1,
},
}
);
return message.channel.send(`${chosenEvent1} You earned ${randomNumber1} reputation!`);
}
} else if (!message.member.roles.cache.has('roleid#2')) {
return message.channel.send(`${chosenEvent2} You earned ${randomNumber1} reputation!`);
}
},
};

Import large amounts of data, but do a .find() for each element

I have a collection of customers of 60.000 items. I need to import a list of people, of 50.000. But for each person, I need to find the ID of the customer and add that to the object that is being inserted.
How should this be done most efficently?
export default async ({ file, user, database }: Request, res: Response) => {
try {
const csv = file.buffer.toString("utf8");
let lines = await CSV({
delimiter: "auto" // delimiter used for separating columns.
}).fromString(csv);
let count = {
noCustomer: 0,
fails: 0
};
let data: any = [];
await Promise.all(
lines.map(async (item, index) => {
try {
// Find customer
const customer = await database
.model("Customer")
.findOne({
$or: [
{ "custom.pipeID": item["Organisasjon - ID"] },
{ name: item["Person - Organisasjon"] }
]
})
.select("_id")
.lean();
// If found a customer
if (!isNil(customer?._id)) {
return data.push({
name: item["Person - Navn"],
email: item["Person - Email"],
phone: item["Person - Telefon"],
customer: customer._id,
updatedAt: item["Person - Oppdater tid"],
createdAt: item["Person - Person opprettet"],
creator: users[item["Person - Eier"]] || "5e4bca71a31da7262c3707c5"
});
}
else {
return count.noCustomer++;
}
} catch (err) {
count.fails++;
return;
}
})
);
const people = await database.model("Person").insertMany(data)
res.send("Thanks!")
} catch (err) {
console.log(err)
throw err;
}
};
My code just never sends an response If I use this as a Express request.

Firebase - Filtering data from two arrays

Currently started learning firebase . I want to compare data from two tables. There is a table 'subscribers' and 'clubMembers'. 'clubMembers' contains the full list of users whereas the 'subscribers' contains the list only those user who have subscribed for the event.
I want to compare emails from both table and extract the ones those are not in 'subscribers' table. So to be make more clear if 'clubMember' have 10 emails, and 'subscribers' have 5 emails, so I want the 5 remaining subscriber email who doesn't have subscribed.
here is the code
db.ref('subscribers/' + today).orderByChild("email").once('value').then(snap => {
db.ref('clubMembers').orderByChild("email").once('value') .then(snapshot => {
const finalNames = [];
const allSubscribers = snap.val();
const allMembers = snapshot.val();
for (const user in allMembers) {
const userObject = allMembers[user];
for(const subUser in allSubscribers){
const subUserObject = allSubscribers[subUser];
if (userObject.email !== subUserObject.email) {
finalNames.push(userObject.email);
}
}
}
the finalNames variable displays the full list of emails, not the filtered ones.
this code get to toy diffrence of array after this code and get data is ok from firebase :
db.ref('subscribers/' + today).orderByChild("email").once('value').then(snap => {
db.ref('clubMembers').orderByChild("email").once('value') .then(snapshot => {
const finalNames = [];
const allSubscribers = snap.val();
const allMembers = snapshot.val();
var res = allMembers.filter(item1 =>
!allSubscribers.some(item2 => (item2.email === item1.emial)))
console.log(res);
var allMembers = [
{ id: 0, email: 'john#a.com' },
{ id: 1, email: 'mary#a.com' },
{ id: 2, email: 'pablo#a.com' },
{ id: 3, email: 'escobar#a.com' }
];
var allSubscribers = [
{ id: 0, email: 'john#a.com' },
{ id: 1, email: 'mary#a.com' }
];
var res = allMembers.filter(item1 =>
!allSubscribers.some(item2 => (item2.email === item1.email)))
console.log(res);

Resources