How to fix Invalid destructuring assignment target? - javascript

What I can do in order to fix my problem? I'm a new newbie in javascript and any recomendations or advices could be helpful to me.
var user = {
username: "Andrey",
password: "JavaScript"
},
{
username: "Max",
password: "12345"
},
{
username: "Pasha",
password: "OWL"
};
var database = [user];
var newsfeed = [
{
username: "Bobby",
timeline: "DOOOOOOG!",
},
{
username: "Max",
timeline: "CAAAAT!",
},
{
username: "Lida",
timeline: "John Ceeeenaaaa!",
}
];
var userNamePrompt = prompt("Your Username?");
var passwordPrompt = prompt("Your password?");
function isUserValid(Name, Pass){
for (var i=0; i<database.length; i++){
if (database[i].username === Name &&
database[i].password === Pass) {
return true;
}
}
return false;
}
function SignIn (Name, Pass){
if (isUserValid(Name, Pass)) {
console.log(newsfeed);
}
else {
alert("Sorry smt went wrong!");
}
}
SignIn (userNamePrompt, passwordPrompt);
If the code is working correctly, i should get back an array with a newsfeed, but instead im getting:
Invalid destructuring assignment target

You wrote: var user = { property }{ property }{ property } which doesn't work. This is probably what you meant ( also skips the var database = [ user ]; assignment):
var database = [
{
username: "Andrey",
password: "JavaScript"
},
{
username: "Max",
password: "12345"
},
{
username: "Pasha",
password: "OWL"
};
]

Related

How to use mongoose custom validator

I have a mongoose schema that I want to validate. What I want to do is to check for whenever the age is present, then birthYear cannot be empty. I have tried both the required and validate property but it isn't working :(
const mongoose = require('mongoose');
const person = new mongoose.Schema({
age: { type: Number },
birthYear: {
type: String,
required: function () {
return this.age&& !this.age.length;
},
validate: [validates, 'Cannot be empty']
},
fullName: { type: String }
})
function validates(value) {
return this.age && !value;
}

Creating a obj name with data in it in vue.js

I just created a constructor function to create new Users for a JSON file.
The structure should be like:
{
"users": {
"userName1": {
"salary": [
"1234"
]
},
"userName2": {
"salary": [
"4321"
]
}
}
}
My code looks like this atm:
export const userDataControllerMixin = {
data() {
return {
userObj: {},
};
},
methods: {
NewUser(user, salary) {
this.user = user;
this.salary = salary;
user = {
salary,
};
},
// GETTING INPUT FROM USERS DIALOGBOX
getInput(inputName, inputSalary) {
const userName = document.querySelector(inputName).value;
const userSalary = document.querySelector(inputSalary).value;
const userData = new this.NewUser(userName, userSalary);
console.log(userData);
},
The structur i get is wrong, it looks like this:
NewUser {user: "asd ", salary: "123"}
When you use the word this, it means the current father, in your case NewUser
To get the variable the way you want, you need to do this:
NewUser(user, salary) {
this[user] = {
'salary':salary
};
},
In VueJS there is no need for querySelectors, since inputs are binded with v-model
Check out: https://v2.vuejs.org/v2/guide/forms.html
Because of that, we can reduce the app to one function, that reads the username and salary properties and adds them to the userObj.
I've made a working example here: https://codepen.io/bergur/pen/agZwQL?editors=1011
new Vue({
el: '#app',
data() {
return {
username: '',
salary: '',
userObj: {}
}
},
methods: {
newUser() {
this.userObj[this.username] = {
salary: [Number(this.salary)]
}
console.log(this.userObj)
}
}
})

Stripe : Error: Received unknown parameter: bank_account[bank_name]

I have been trying to add a bank_name to my Stripe Connect user's external account, but I keep getting an error as if I am misreading the documentation on the function.
Error: Received unknown parameter: bank_account[bank_name]
The documentation shows that I should be able to access the bank_name from the bank_account object, but my error is narrowed down to it being null. My console.log(newValue.externalAccount.bankName) returns the bankName as expected that was entered, so it isn't null going in. Any idea why I am getting this error?
Firebase Function:
exports.createStripeAccount = functions.firestore
.document("users/{userId}")
.onUpdate(async (change, context) => {
const newValue = change.after.data();
const previousValue = change.before.data();
if (newValue.state === "technician" && previousValue.state === "client") {
try {
const account_add_response = await stripe.accounts.create(
{
type: "custom",
country: "US",
requested_capabilities: ["platform_payments"],
email: newValue.email,
tos_acceptance: newValue.stripeTosAcceptance,
business_type: "individual",
business_profile: {
url: newValue.socialLinks.linkedin
},
individual: {
first_name: newValue.firstName,
last_name: newValue.lastName,
gender: newValue.gender,
email: newValue.email,
phone: newValue.phone,
address: {
line1: newValue.address.line1,
line2: newValue.address.line2,
city: newValue.address.city,
state: newValue.address.state,
postal_code: newValue.address.zip,
country: newValue.address.country
},
ssn_last_4: newValue.technician.ssnLast4,
dob: {
day: newValue.dob.day,
month: newValue.dob.month,
year: newValue.dob.year
}
}
},
async function(error, account) {
if (error) {
return console.error(error);
} else {
console.log(
"Writing account.id " + account.id + " to user DB..."
);
console.log("newValue.externalAccount.bankName: " + newValue.externalAccount.bankName)
const bank_add_response = await stripe.accounts.createExternalAccount(
account.id,
{
external_account: {
object: "bank_account",
country: "US",
currency: "USD",
account_holder_name:
newValue.externalAccount.accountHolderName, // Have user input manually, might be different than user's name
account_holder_type: "individual",
bank_name: newValue.externalAccount.bankName,
routing_number: newValue.externalAccount.routingNumber,
account_number: newValue.externalAccount.accountNumber
}
},
function(error, bank_account) {
if (error) {
return console.error(error);
} else {
console.log(
"Writing bank_account.id " +
bank_account.id +
" to user DB..."
);
return admin
.firestore()
.collection("users")
.doc(context.params.userId)
.set(
{
connectId: account.id,
externalAccount: {
bankAccountId: bank_account.id,
bankName: bank_account.bank_name,
last4: bank_account.last4,
}
},
{ merge: true }
);
}
}
);
}
}
);
} catch (error) {
console.log(error);
await change.ref.set(
{ error: userFacingMessage(error) },
{ merge: true }
);
return reportError(error, { user: context.params.userId });
}
}
});
Looks like I misunderstood the purpose of the bank_name field. I thought it was for a custom name the user defines about their bank account, like "Doug's Chase Checkings", but it seems that it's auto generated by Stripe and read only.

How to search in a REST API express with multiple fields

I would like to perform a search request like https://api.mywebsite.com/users/search?firstname=jo&lastname=smit&date_of_birth=1980
I have a User schema like:
var UserSchema = new mongoose.Schema({
role: { type: String, default: 'user' },
firstname: { type: String, default: null },
lastname: { type: String, default: null },
date_of_birth: { type: Date, default: null, select: false },
});
What I did so far with stackoverflow help:
// check every element in the query and perform check function
function search_t(query) {
return function (element) {
for (var i in query) {
if (query[i].function(element[i], query[i].value) == false) {
return false;
}
}
return true;
}
}
// prepare query object, convert elements and add check function
// convert functions are used to convert string (from the query) in the right format
// check functions are used to check values from our users
function prepareSearch(query, cb) {
let fields = {
"firstname": {
"type": "string",
"function": checkString,
"convert": convertString
},
"lastname": {
"type": "string",
"function": checkString,
"convert": convertString
},
"date_of_birth": {
"type": "date",
"function": checkDate,
"convert": convertDate
}
};
for (let k in query) {
k = k.toLowerCase();
if (!(k in fields)) {
return cb({message: "error"});
}
query[k] = {value: fields[k].convert(query[k]), function: fields[k].function};
}
return cb(null, query);
}
// linked to a route like router.get('/search/', controller.search);
export function search(req, res) {
return User.find({}).exec()
.then(users => {
return prepareSearch(req.query, (err, query) => {
if (err) {
return handleError(res)(err);
} else {
return res.status(200).send(users.filter(search_t(query)));
}
});
})
.catch(handleError(res));
}
So this code works but I don't know if it's a good thing. I have a lot of other fields to check (like gender, ....) and I don't know if it's a good thing to do it "manually".
I don't know if mongoose has any function to do it.
Should I use another method to filter / search in my users in my REST API ?
I'm pretty new here and I am not sure about how I work...
Thank you,
Ankirama

I want to search whether username and password is presenty in my json or not

I have tried many ways of doing this but it is just not getting me what i am looking for.I have no idea about JSON,this is what I could understand from net.
var loginDataList = [{
"username": "abc",
"password": "abc123"
}, {
"username": "richa",
"password": "richa123"
}];
var jsonString = JSON.stringify(loginDataList);
if ((username in jsonString) && (password in jsonString))
alert("woola");
else
alert("nope");
I also tried:
if (jsonString.has("username"))
$('h2').text('Woollaaaa ').delay(1000).hide(1);
Any help would be appreciated.
Here you go :
if(jsonString.indexOf('username') && jsonString.indexOf('password')) gives you -1 if it is not present, greater than -1 if present.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
</style>
</head>
<body>
<script>
var loginDataList = [{"username":"abc","password":"abc123"}, {"username":"richa","password":"richa123"}];
var jsonString = JSON.stringify(loginDataList);
console.log(jsonString);
if(jsonString.indexOf('username') && jsonString.indexOf('password')){
alert("Present");
}
else{
alert("Not");
}
</script>
</body>
</html>
var loginDataList = [{
"username": "abc",
"password": "abc123"
}, {
"username": "richa",
"password": "richa123"
}]
var result = loginDataList.map(function(data) {
if (data.username && data.username.trim() != "" && data.password && data.password.trim() != "") {
return "Present"
} else {
return "Not"
}
});
console.log(result);
I think that we must find not keys username and password but certain values, so we need traverse our array of objects:
var loginDataList = [
{'username': 'abc', 'password': 'abc123'},
{'username': 'abcd', 'password': 'abc1234'},
{'username': 'richa', 'password': 'richa123'}
];
var username = 'abcd';
var password = 'abc1234';
var userAndPasswordPresent = false;
for (var i in loginDataList) {
if (loginDataList[i].username === username && loginDataList[i].password === password) {
userAndPasswordPresent = true;
}
}
console.log(userAndPasswordPresent);
Based on comments below you want to check whether the username and password match with any one object in the JSON.
Here is the code for that.
function checkUser(uname, pswd){
var loginDataList = [
{
"username": "abc",
"password": "abc123"
},
{
"username": "richa",
"password": "richa123"
}
];
var user = loginDataList.find(function(user){
return user.username === uname && user.password === pswd
});
if(user == null)
{
alert("nope");
}
else
{
alert("woola");
}
}
checkUser("abc","abc123");
Let me know if this works.

Categories