How do I add a new complex entry to a javascript array? - javascript

I have a JavaScript data structure like the following in my Node.js/Express web app:
var users = [
{ username: 'x', password: 'secret', email: 'x#x.com' }
, { username: 'y', password: 'secret2', email: 'y#x.com' }
];
After receiving posted form values for a new user:
{
req.body.username='z',
req.body.password='secret3',
req.body.email='z#x.com'
}
I'd like to add the new user to the data structure which should result in the following structure:
users = [
{ username: 'x', password: 'secret', email: 'x#x.com' }
, { username: 'y', password: 'secret2', email: 'y#x.com' }
, { username: 'z', password: 'secret3', email: 'z#x.com' }
];
How do I add a new record to my users array using the posted values?

You can use the push method to add elements to the end of an array.
var users = [
{ username: 'x', password: 'secret', email: 'x#x.com' }
, { username: 'y', password: 'secret2', email: 'y#x.com' }
];
users.push( { username: 'z', password: 'secret3', email: 'z#x.com' } )
You could also just set users[users.length] = the_new_element but I don't think that looks as good.

You can add items to an array in many ways:
Push - adds to the end (think stack)
Unshift - adds to the beginning (think queue)
Splice - generic (push and unshift are wrappers around this)

Related

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);

Nested JSON object not saving to database MongoDB

I have three mongo schemas, each nest into one another. The main one has a nested JSON, which also has a nested JSON inside that. However, when the User is saved using the main Schema, the other two nested schemas aren't being saved with their default values, why? Here's an example of my three schemas (just an example data structure):
const userContacts = new mongoose.Schema({
user1PhoneNumber: {
type: Number,
default: 0
},
user2PhoneNumber: {
type: Number,
default: 0
}
})
const contact = new mongoose.Schema({
phoneNumber: {
type: Number,
default: 0
},
contacts: {
type: userContacts
}
})
const finalUserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
max: 255
},
email: {
type: String,
required: true,
max: 255,
},
password: {
type: String,
required: true,
min: 10,
max: 1024,
},
contactDetails: {
type: contact
}
})
module.exports = mongoose.model('User', finalUserSchema);
When the user is first created using the mongoose model, the values aren't set as they will be used later on...but they should still appear in the database with their default values:
const user = new User({
username: req.body.username,
email: req.body.email,
password: hashedPassword,
});
What gets saved in the database:
Where is the contactDetials nested JSON object with it's default values, I shouldn't have to provide any data when I first save the user as it should just use the data model with its default values?
May you should try this:
contactDetails: contact
instead of:
contactDetails: {type: contact}
same for Contacts

I need to unstructure an object to update the variables defined in data

it's my first post. I need to destructure to update a variable defined in "data", I have the following code snippets. I'm using VUE.
data: () => ({
id: '',
phone: '',
email: ''
}),
methods: {
async getId(){
{this.id, this.email, this.phone} = this.$route.query.item
}
}
Actually you can assign to existing variables.
The syntax is just a little weird.
This should work
({id: this.id, phone: this.phone, email: this.email} = this.$route.query.item)
Here's a working example
You can't destructure to existing props but to new ones only:
data () {
return {
item: {
id: '',
phone: '',
email: ''
}
}
},
...
methods: {
async getId(){
{ id, email, phone } = this.$route.query.item
Object.assign(this.item, { id, email, phone })

Is there a better way to use applySpec here

I think the redundancy here can be removed by using some function insde ramda but I am very new to this library so i cant think of how.Some help would be really appreciated
let lib = {
getFormattedPropsForUser: R.compose(
R.pickBy(R.identity),
R.applySpec({
username: R.prop('username'),
password: R.prop('password')
})),
getFormattedQueryParamsForUser: R.compose(
R.pickBy(R.identity),
R.applySpec({
_id: R.prop('_id'),
username: R.prop('username'),
password: R.prop('password')
})
)
};
Extract the common part of both applications to a function, and add the ability to add more items to the spec using partial application and object spread.
Example:
const forUser = spec => R.compose(
R.pickBy(R.identity),
R.applySpec({
...spec,
username: R.prop('username'),
password: R.prop('password')
})
)
const lib = {
getFormattedPropsForUser: forUser(),
getFormattedQueryParamsForUser: forUser({ _id: R.prop('_id') }),
}
const test = { _id: 'id', username: 'username', password: 'password' }
console.log(lib.getFormattedPropsForUser(test))
console.log(lib.getFormattedQueryParamsForUser(test))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
I think you can simplify your functions quite a bit, and abstract the common parts out relatively easily. Here getActualProps does much the same as your applySpec/pickBy(identity) shuffle, with the actual fields parameterized. Then the two functions (or library methods) can be written in terms of it.
const getActualProps = (names) => pickBy((v, k) => includes(k, names))
const getFormattedPropsForUser = getActualProps(['username', 'password'])
const getFormattedQueryParamsForUser = getActualProps(['_id', 'username'])
// Test
const fred = {_id: 1, name: 'fred', username: 'fflint', password: 'dino'}
const wilma = {_id: 2, name: 'wilma', username: 'wilma42'}
const barney = {_id: 3, name: 'barney', password: 'bam*2'}
console.log(getFormattedPropsForUser(fred)) //~> {password: "dino", username: "fflint"}
console.log(getFormattedQueryParamsForUser(fred)) //~> {_id: 1, username: "fflint"}
console.log(getFormattedPropsForUser(wilma)) //~> {username: "wilma42"}
console.log(getFormattedQueryParamsForUser(wilma)) //~> {_id: 2, username: "wilma42"}
console.log(getFormattedPropsForUser(barney)) //~> {password: "bam*2"}
console.log(getFormattedQueryParamsForUser(barney)) //~> {_id: 3}
<script src="https://bundle.run/ramda#0.26.1"></script><script>
const {pickBy, includes} = ramda </script>

Firebase Functions - Loop through event value [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
A firebase event which listents for changes.
exports.sendTestEmail = functions.database.ref('/email/{pushID}')
.onWrite(event => {
// Only edit data when it is first created.
if (event.data.previous.exists()) {
return;
}
// Exit when the data is deleted.
if (!event.data.exists()) {
return;
}
return sendTestEmail(event);
});
function sendTestEmail(email, event) {
const users = event.data.val();
console.log(users);
});
}
this is the result for console.log(users):
{ '-Km8VHEPHExBtpIN_7q0':
{ admin: 'false',
birthday: '76',
description: 'desc',
email: 'user#gmail.com',
first_name: 'fname',
last_name: 'lname',
level: 5,
occupation: 'dev',
occupationLevel: 'dev5',
phone: '+8766',
verified: false },
'-KmSjAaxdCUvrPEQ8InI':
{ admin: 'false',
birthday: '1990',
description: 'desc',
email: 'email2#gmail.com',
first_name: 'fname',
last_name: 'lanam3',
level: 4,
occupation: 'dev',
occupationLevel: 'dev4',
phone: '+23434',
verified: false } }
I can't seem to loop and get the emails which are needed for sending emails to users who own the email addresses.
Maybe consider something like this.
function sendTestEmail(event) {
emails = []; // create empty email array
const users = event.data.val(); // get users, as you currently were.
for (var key in users) { // loop through users to retrieve key.
var email = users[key].email; // get email using key
emails.push(email); // push to emails array
}
return emails;
}

Categories