Node.js undefined properties - javascript

I'm trying to create a log in window. My code is simple.
var employees = {
'1' : {
firstName: '',
lastName: '',
login: 'qwerty',
password: '12345',
},
'2' : {
login: 'asdfg',
password: '12345',
},
};
app.post('/main', function(req, res) {
if (!req.body) return res.sendStatus(400);
console.log(req.body);
for (var key in employees) {
console.log(key['login']);
console.log(key['password']);
if ((key.login == req.body.login) && (key.password == req.body.password)) {
res.render('main');
} else {
app.get('/', function(req,res) {
res.send(createIndexPage());
});
};
};
});
Why key.login and key.password return undefined?
And why else block does not run when if statement is wrong?

Look at what the value of key actually is:
var employees = {
'1': {
firstName: '',
lastName: '',
login: 'qwerty',
password: '12345',
},
'2': {
login: 'asdfg',
password: '12345',
},
};
for (var key in employees) {
console.log(key);
}
It is the property name (as a string), not the value of the property.
console.log(employees[key]['login']); will give you what you are looking for.

Related

Validate optional string with Yup?

I'm trying to validate a string with Yup:
const schema = object({
firstname: string().optional().nullable().notRequired().min(2),
});
The rules should be a string but can be null or empty, and if there is a value, then the length must be more than 2.
But for some reason, it's not working:
const shouldWorks = [
{ firstname: 'bla' },
{ firstname: '' }, <--- its failed here.. empty is okay (.notRequired)
{ firstname: null },
];
How do I change the schema to fit my rules?
stackblitz
import { object, string } from 'yup';
console.clear();
const shouldWorks = [
{ firstname: 'bla' },
{ firstname: '' },
{ firstname: null },
];
const shouldNotWork = [{ firstname: 'a' }];
const schema = object({
firstname: string().optional().nullable().notRequired().min(2),
});
shouldWorks.forEach((obj, i) => {
console.log(`test: ${i}`);
schema.validateSync(obj);
});
shouldNotWork.forEach((obj, i) => {
try {
schema.validateSync(obj);
console.log(`error test: ${i} failed`);
} catch (e) {
console.log(`error test: ${i} pass`);
}
});
You can use yup.lazy to lazily decide what validators to use based on the value:
const schema = object({
firstname: lazy((value) =>
value === ''
? string()
: string().optional().nullable().notRequired().min(2)
),
});
Stackblitz

postman returning null with 200 status code

getting null value as response with 200 status code. i want to see the profile details as response but instead of that showing null value with no error status code in my postman i dont find any error on my code. why it shows like this ? i want to see profile details as response after sending
Router.post
router.post(
'/',
[
auth,
[
check('status', 'Status is required').not().isEmpty(),
check('skills', 'Skills cannot be empty').not().isEmpty(),
],
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
company,
website,
location,
bio,
status,
githubusername,
skills,
youtube,
twitter,
instagram,
linkedin,
} = req.body;
const profileFields = {};
profileFields.user = req.user.id;
if (company) profileFields.company = company;
if (website) profileFields.website = website;
if (location) profileFields.location = location;
if (bio) profileFields.bio = bio;
if (status) profileFields.status = status;
if (githubusername) profileFields.githubusername = githubusername;
if (skills) {
profileFields.skills = skills.split(',').map(skill => skill.trim());
}
// creating object for socila links
profileFields.social = {};
if (youtube) profileFields.social.youtube = youtube;
if (twitter) profileFields.social.twitter = twitter;
if (instagram) profileFields.social.instagram = instagram;
if (linkedin) profileFields.social.linkedin = linkedin;
try {
let profile = await Profile.findOne({ user: req.user.id });
if (profile)
//update
profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
);
return res.json(profile);
// create
profile = new Profile(profileFields);
await profile.save();
res.json(profile);
} catch (err) {
console.error(err);
res.status(500).send('server error');
}
}
);
here is profile schema looks like
const ProfileSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
company: {
type: String,
},
website: {
type: String,
},
status: {
type: String,
required: true,
},
location: {
type: String,
},
skills: {
type: [String],
required: true,
},
bio: {
type: String,
},
githubusername: {
type: String,
},
experience: [
{
title: {
type: String,
required: true,
},
company: {
type: String,
required: true,
},
location: {
type: String,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
education: [
{
school: {
type: String,
required: true,
},
degree: {
type: String,
required: true,
},
fieldofstudy: {
type: String,
required: true,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
social: {
youtube: {
type: String,
},
twitter: {
type: String,
},
linkedin: {
type: String,
},
instagram: {
type: String,
},
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Profile = mongoose.model('profile',ProfileSchema)
your code logic has problem.
let profile = await Profile.findOne({ user: req.user.id }); if (profile) //update profile = await Profile.findOneAndUpdate( { user: req.user.id }, { $set: profileFields }, { new: true } ); return res.json(profile);
here, if you can't find the record in database, you still return and there is no value so that you got null response. i suggest you remoe the return res.json(profile); into if statement
Back to the basics, the if statement.
if (profile){
//update
profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
);
return res.json(profile);
}
You need to use brackets {}.
In your code, return res.json(profile); gets fired no matter if the response is null or not
the problem is with your syntax you need to add curly braces
if (profile){
//update
profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
)};

Login-Validation If Else Statement Problem

Why when I have else statement added like this, the if statement is ignored. I put values that are true and the if statement is ignored the output always is my else code...
$(document).ready(function() {
let userData = [
{
email: 'knorr#live.com',
password: 'ksGuQbzYPpW'
},
{
email: 'rddesign#msn.com',
password: '9Q6urHqy'
},
{
email: 'chaffar#yahoo.ca',
password: '4xaz2pyk'
},
{
email: 'fatelk#mac.com',
password: 'TAePJSb2ACX'
},
{
email: 'luebke#me.com',
password: 'EyFY8uhX'
},
{
email: 'amichalo#mac.com',
password: 'c7muQ6bxcA9QJKS'
},
{
email: 'mallanmba#yahoo.ca',
password: 'NqCGLmGtcFU'
},
{
email: 'isaacson#att.net',
password: 'PMjRGUug7Ff73Kt'
},
{
email: 'aracne#aol.com',
password: 'sBJU7JJR7Qx6f55'
},
{
email: 'boser#comcast.net',
password: 'DMXQRNj7BHZ'
},
{
email: 'gtaylor#verizon.net',
password: 'AbefrKfkbxHbP3u'
},
{
email: 'firstpr#comcast.net',
password: 'PGWPUtcwP'
},
{
email: 'sumdumass#sbcglobal.net',
password: '2DrCpjkk9mm8bjW'
},
{
email: 'campbell#yahoo.com',
password: 'ZmYZgaDq6'
},
{
email: 'wetter#me.com',
password: 'ppTG3pGAe'
},
{
email: 'british#verizon.net',
password: '67SbpGYvPJ2'
}
];
$("#loginBtn").on("click", function() {
let email = $("#email").val();
let password = $("#pass").val();
for (let i = 0; i < userData.length; i++) {
if (email === userData[i].email) {
if (password === userData[i].password) {
alert("Match");
} else if (password !== userData[i].password) {
alert("Incorrect Password");
}
break;
} else {
alert("Invalid Login");
}
}
});
});
I think it works, except it doesn't appear that it does. Because the if statement is in the loop, for every element in userData that is incorrect, "Invalid Login" will appear.
Your code doesn't ignore your if statement. It works. You may try something like this:
$(document).ready(function () {
let userData = [{ email: 'admin',
password: '1234'
}, {
email: 'admin2',
password: '12345'
}];
$("#loginBtn").on("click", () => {
let email = $("#email").val();
let password = $("#pass").val();
let pos = userData.map((user) => user.email).indexOf(email);
if (pos !== -1) {
alert((userData[pos].password === password) ? "match"
: "password invalid");
} else { alert("user not found"); }
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email" type="text"/>
<input id="pass" type="password"/>
<button id="loginBtn">Login</button>
Your code is okay and it works even if it has a lot of security matters. I tested myself and at a certain using a pair email and pass from the array there is a MATCH:
<html>
<body>
<input id="email">
<input id="password">
<button id="sub" type="button">Sbmit</button>
<script>
let userData = [
{
email: 'knorr#live.com',
password: 'ksGuQbzYPpW'
},
{
email: 'rddesign#msn.com',
password: '9Q6urHqy'
},
{
email: 'chaffar#yahoo.ca',
password: '4xaz2pyk'
},
{
email: 'fatelk#mac.com',
password: 'TAePJSb2ACX'
},
{
email: 'luebke#me.com',
password: 'EyFY8uhX'
},
{
email: 'amichalo#mac.com',
password: 'c7muQ6bxcA9QJKS'
},
{
email: 'mallanmba#yahoo.ca',
password: 'NqCGLmGtcFU'
},
{
email: 'isaacson#att.net',
password: 'PMjRGUug7Ff73Kt'
},
{
email: 'aracne#aol.com',
password: 'sBJU7JJR7Qx6f55'
},
{
email: 'boser#comcast.net',
password: 'DMXQRNj7BHZ'
},
{
email: 'gtaylor#verizon.net',
password: 'AbefrKfkbxHbP3u'
},
{
email: 'firstpr#comcast.net',
password: 'PGWPUtcwP'
},
{
email: 'sumdumass#sbcglobal.net',
password: '2DrCpjkk9mm8bjW'
},
{
email: 'campbell#yahoo.com',
password: 'ZmYZgaDq6'
},
{
email: 'wetter#me.com',
password: 'ppTG3pGAe'
},
{
email: 'british#verizon.net',
password: '67SbpGYvPJ2'
}
];
document.getElementById("sub").addEventListener("click", function() {
let email = document.getElementById("email").value;
console.log(typeof email);
let password = document.getElementById("password").value;
for (let i = 0; i < userData.length; i++) {
console.log(typeof userData[i].email);
if (email === userData[i].email) {
if (password === userData[i].password) {
alert("Match");
} else if (password !== userData[i].password) {
alert("Incorrect Password");
}
break;
} else {
alert("Invalid Login");
}
}
});
</script>
</body>
</html>

Not able to read the below data as per requirement ( in java script)

bigQuery.query({
query:'Select email from table',
useLegacySql: false
}).then(function (rows) {
setValue(rows);
});
function setValue(value) {
someVar = value;
console.log(someVar);
The output in console is this-:
[ [ { email: 'v28#gmail.com' },
{ email: 'v29#gmail.com' },
{ email: 'v30#gmail.com' },
{ email: 'v31#gmail.com' } ] ]
And i want the output like:
v28#gmail.com
v29#gmail.com
v30#gmail.com
v31#gmail.com
How to access some someVar to get the below output??
Please help me to solve this

Map dynamically array to nested object

I want to retrieve the form content on a submit and map that data into an object.
let userData = $(e.currentTarget).serializeArray();
let userDataObject = this.serializedToObject(userData);
--
Template objects to send through POST
serializedToObject(serializedArray) {
let templateObject = {
privider: '',
pop3: {
host: '',
port: 110,
ssl: false
},
imap: {
host: '',
port: 993
},
email: '',
password: ''
};
for (let data in serializedArray) {
}
return templateObject;
}
--
The form of the userData is
[Object, Object, Object, Object, Object, Object, Object]
-- While on object is of form
Object: {
name: 'provider',
value: 'Aladin'
}
Object: {
name: 'imap-host',
value: '955'
}
Object: {
name: 'imap-port',
value:
}
Object: {
email: 'test#gmail.com',
value:
}
So I need some help to map that array of objects to the templateObject.
AnyHelp will be highly appreciated.
Update
[{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george#google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}]
The name-property of each serializedArray's object has a minus-character (-) representing nested objects, you can split by those characters and then set the values of your templateObject's properties:
var serializedArray = [{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george#google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}];
// your defaults
var templateObject = {
provider: '',
pop3: {
host: '',
port: 110,
ssl: false
},
imap: {
host: '',
port: 993
},
email: '',
password: '',
};
serializedArray.forEach(function(obj) {
var deep = obj.name.split('-');
var key = deep.pop();
var level = templateObject;
deep.forEach(function(inner) {
var nested = level[inner];
var isObject = Object(nested) === nested;
level = isObject ? nested : {};
});
level[key] = obj.value;
});
// return templateObject; // when inside your function
console.log(templateObject);
You can also use reduce method, in a more functional way
const array = [{
name: 'provider',
value: 'Aladin'
},{
name: 'imap-host',
value: '955'
},{
name: 'imap-port',
value: 'something'
}];
const newObject = array.reduce( (acc, item, {}) => {
acc[item.name] = item.value;
return acc;
})
console.log(newObject);
Link to fiddle: https://jsfiddle.net/y5xkddnn/
There is too much overhead to iterate serialized array and map it to the nested object.
Please consider this approach, which is less complicated:
let userData = new FormData($(e.currentTarget)[0]);
let userDataObject = serializedToObject(userData);
function serializedToObject(data) {
return {
provider: data.get('provider'),
pop3: {
host: data.get('pop3-host'),
port: data.get('pop3-port'),
ssl: data.get('pop3-ssl')
},
imap: {
host: data.get('imap-host'),
port: data.get('imap-port')
},
email: data.get('email'),
password: data.get('password')
};
}
I guessed some fields here. Please correct them if needed.

Categories

Resources