Javascript array becoming null after second run - javascript

'''
const users = []
const addUser = ({ id, username, room }) => {
// Clean the data
username = username.trim().toLowerCase()
room = room.trim().toLowerCase()
// Validate the data
if (!username || !room) {
return {
error: 'Username and room are required'
}
}
// Check for existing user
const existingUser = users.find((user) => {
return user.username === username || user.room === room
})
// Validate username
if (existingUser) {
return {
error: 'Username already exists!'
}
}
// Store user
const user = { id, username, room }
users.push(user)
return { user }
}
addUser({
id: 03,
username: 'rohan',
room: 'playground'
})
console.log(users)
'''
If I run this in console the output is [ { id: 3, username: 'rohan', room: 'playground' } ]
But again if i just comment out the call and print the array. It showing empty.
'''
//addUser({
// id: 03,
// username: 'rohan',
// room: 'playground'
//})
console.log(users)
'''
From first run the value stored in object so It must be in the users array forever. Why this is empty if I dnt add value?

The following demo features 2 separate objects (userObjA, and userObjB), an arrow function called addUser(...user) which can accept any number of given objects (because of the spread operator: ... magic) then returns said objects wrapped in an array of objects (users).
Note: no const were hurt during the demonstration -- healthy free range let are leveraged for painless declarations and assignments.
Demo
let userObjA = {
id: 3,
name: 'Rohan',
room: 'Suite 42'
};
let userObjB = {
id: 4,
name: 'Dell',
room: 'Single 601'
};
const addUser = (...user) => {
let users = [];
users.push(user);
return users.flat();
};
console.log(addUser(userObjA, userObjB));

Related

filter function not working in an Array using Node js

I am trying to filter out empty array but its not happening
I was trying to compare value which are present inside my database and fileName
I tried arr.filter(Boolean);
even i tried arr.filter((item)=>item)
PS: fileName is not an array value so I converted it into array.
function checkDoc(data, childProduct, fileName, pathName, req, res) {
return new Promise((resolve, reject) => {
Document.findAll({
raw: true,
where: {
product_id: childProduct.id,
},
})
.then((productDoc) => {
if (productDoc.length === 0) {
return resolve(addDocument(data, childProduct, fileName, pathName));
} else {
let fileArray = [];
fileArray.push(fileName);
productDoc.forEach((singleProduct) => {
let productValue = singleProduct.name;
let unMatchedValues = fileArray.filter((value) =>
productValue.includes(value)
);
let removedBoolean = unMatchedValues.filter((item) => item);
console.log("Document Name: ", removedBoolean);
});
}
})
.catch(function (err) {
return reject("Can't be added please try again :) " + err);
});
});
}
fileName:
ABC
PQR
XYZ
Installation and Configuration
Java
Node Js
where as in singleProduct.name it contain
[ABC]
[PQR]
[Installation and Configuration]
[XYZ]
attached Output Image :
Expected OutPut:
matchedValue:
[`document name: ABC`]
[`document name: PQR`]
[`document name: Installation and configuration`]
[`document name: XYZ`]
unmatchedValue:
['Java']
[`Node Js`]
If you're asking how to filter an array of objects to remove those with empty names, here's an example:
const team = [
{ name: 'max', age: 21 },
{ name: '', age: 19 },
{ name: 'james', age: 33 },
{ name: '', age: 30 },
];
// Log the entire team
console.log('Team:', team);
// Log only those team members with names
console.log('Team with names:', team.filter(x => x.name));
// Log only the names
console.log('Names:', team.filter(x => x.name).map(x => x.name));

Update data many-to-many in typeorm express

i tried both .save and .update but it cause an error, --in the case of .save it return error: the value of a duplicate key breaks the unique constraint --in .update case it return error: the "userId" column of the "user" relation does not exist
note: i have 2 tables role and user and the association user_role
//Many-to-many relation with user
#ManyToMany((type) => User, (user) => user.roles)
users: User[];
//Many-to-many relation with role
#ManyToMany((type) => Role, {
cascade: true,
})
#JoinTable({
name: "users_roles",
joinColumn: { name: "userId", referencedColumnName: "id" },
inverseJoinColumn: { name: "roleId" }
})
roles: Role[];
the source code is :
/* exemple of data
entity2 = {
username: 'user8',
password: 'user8',
firstname: 'test',
lastname: 'tt',
email: 'user8#gmail.com',
company: 18,
roles: [ { id: 62 }, { id: 63 } ]
} */
let entity = await this.userRepository.create(data.payload);
let entity2 = { ...entity, roles: data.payload.selectedRoles }
const user = await this.userRepository.save(entity2);
/*const user = await this.userRepository.update(id, entity2);*/
//todo we need to serialize the user
// return only what we need like username , email, ...etc not password!!!!
return { success: true, user: SanitizeUser(user) };
I did findone then .save, 1st get the data to update using data= this.userRepository.findOne(id) then you can apply userRepository.save(data) to this data. for example :
const userUpdated = await this.userRepository.findOne(id)
let dataUpdated = {
...userUpdated,
username: data.payload.username,
firstname: data.payload.firstname,
lastname: data.payload.lastname,
email: data.payload.email,
company: data.payload.selectedCompany,
roles: data.payload.selectedRoles
}
const user = await this.userRepository.save(dataUpdated);

Dynamic name of array in document using doc().set- Firebase function

I am not able to assign dynamic name to my array (I want to assign value of auth_ID as name of array).
Problem - it is saving auth_ID as text in db, whereas i want its value.
Here is my code:
exports.insert_totalcalllogs = functions.firestore
.document('calllogs/{calllogsId}')
.onCreate(
async (snapshot: { data: () => { (): any; new(): any; entryDate_show:any; authid: any; fullname:any; }; },context:any) => {
// todos details.
const text = snapshot.data();
const entryDate_show = text.entryDate_show;
const auth_ID = text.authid; // want this to be name of array
const fullname = text.fullname;
admin.firestore().collection("totalcalllogs").doc(entryDate_show).set({
auth_ID: [
{ number: 1, fullname: fullname , authid: auth_ID},
],
age: 12,
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error: any) {
console.error("Error writing document: ", error);
});
...// some code
See image of console:
If you want to use a variable as the name of property in a JavaScript object, use the square bracket notation when building the object:
admin.firestore().collection("totalcalllogs").doc(entryDate_show).set({
[auth_ID]: [
{ number: 1, fullname: fullname , authid: auth_ID},
],
age: 12,
})
Note the square brackets around [auth_ID].

Validating req.params with express validator

I want the user to be able to write a specific account number in the endpoint, been trying to validate the endpoint param if it exists in my database. I couldn't get it to work, please what am I doing wrong?
My validation
const validateReq: [
param('accountNumber').exists().custom(acctNo => accountNumberExist(acctNo)),]
My accountNumberExist function
accountNumberExist(inputAcct) {
const isfound = accounts.find(account => account.accountNumber === inputAcct);
if (isfound === undefined) throw new Error('Account Number not found');
}
My accounts file
const accounts = [
{
id: 1,
accountNumber: 1234567890,
createdOn: new Date(),
owner: 1,
type: 'current',
balance: 23444.43,
status: 'active',
},
{
id: 2,
accountNumber: 1234167890,
createdOn: new Date(),
owner: 1,
type: 'savings',
balance: 2233444.43,
status: 'active',
},
{
id: 3,
accountNumber: 9987654321,
createdOn: new Date(),
owner: 2,
type: 'saving',
balance: 73444.43,
status: 'active',
},
];
But this is always throwing the 'Account Number not found' error even though, the req.param exists in my accounts database.
Params are parsed as string by express middleware. Say I make a req to path defined below like /some/1000
app.get('/some/:path', (req, res, next) => {
console.log(typeof req.param.path)
// outputs string
})
So you need to parse the incoming parameter to integer (Number) since you've stored accountNumber as integer. So adding toInt to chain like below should solve it:
const validateReq: [
param('accountNumber').exists().toInt().custom(acctNo => accountNumberExist(acctNo)),
]
accountNumber inside accounts array is a number whereas req.params.accountNumber is a string. You need to convert the data type. You can do it as
accountNumberExist(inputAcct) {
const isfound = accounts.find(account => account.accountNumber.toString() === inputAcct);
if (isfound === undefined) throw new Error('Account Number not found');
}
I think that the problem is your query. find method runs in an asynchronous way, that's why isfound property does not contain the data you expect. Here is a simple approach using promises which works pretty well for me.
// Here is your function.
accountNumberExist(inputAcct) {
return accounts.find({accountNumber: inputAcct})
.then(result => {
if (result.length == 0) {
console.log("Account Number not found");
return Promise.reject('Account Number not found');
}
return Promise.resolve();
});
}

Mongoose partial update of an object

I have a simple user model:
{
_id: "59d72070d9d03b28934b972b"
firstName: "first"
lastName: "last"
email: "first.last#gmail.com"
subscriptions: {
newsletter: true,
blog: true
}
}
I'm trying to do partial updates on the subscriptions object. I'm passing the id of the user and a payload object that can have either one or both properties of the object. Let's say I only want to update newsletter and set it to false. I'll send:
{ id: "59d72070d9d03b28934b972b", payload: { newsletter: false } }
And then:
const user = await User.findByIdAndUpdate(
args.id,
{ $set: { subscriptions: args.payload } },
{ upsert: true, new: true }
);
This will return:
subscriptions: {
newsletter: false
}
Is there a way to only modify the newsletter property when I only pass newsletter in the payload object without deleting the other properties? I know I only have two properties in this example, but in time, the object will keep expanding.
To update only the nested field, use { "subscriptions.newsletter": false } :
const user = (await User.findByIdAndUpdate(
args.id, {
$set: {
"subscriptions.newsletter": args.payload
}
}, {
new: true
}
));
If your input can have missing fields, you can build a dynamic query in $set with only the fields you have specified in your input :
async function save(id, query) {
const user = (await User.findByIdAndUpdate(
id, {
$set: query
}, {
new: true
}
));
console.log(user);
}
var id = mongoose.Types.ObjectId("59d91f1a06ecf429c8aae221");
var input = {
newsletter: false,
blog: false
};
var query = {};
for (var key in input) {
query["subscriptions." + key] = input[key];
}
save(id, query);
I ended up doing the following:
const user = await User.findById(args.id);
// merge subscriptions
user.subscriptions = Object.assign({}, user.subscriptions, args.payload);
return user.save();

Categories