Skip to else if property is undefined - javascript

I have function that creates a team and puts data to database. Now I'm trying to check if team already exists, if it does exists then reply with message. I have problem with my if statement.
if (result[0].teamname == teamName)
When result[0].teamname is undefined it shows Cannot read property 'teamname' of undefined it ignores else and throws an error. How can I make so that does not ignore else?
Here is the function I use to create team.
function createTeam(teamName, members, message) {
teamName = teamName.replace("_", " ");
let insertTeam = `INSERT INTO teams (teamname) VALUES ('${teamName}');`;
db.select(`SELECT id_t, teamname FROM teams WHERE teamname = '${teamName}'`, function(err, result) {
if (err) {
throw err;
} else {
if (result[0].teamname == teamName) {
if (message.guild !== null) message.delete();
message.reply("this team already exists!");
} else {
db.query(insertTeam);
db.select(`SELECT id_t FROM teams WHERE teamname = '${teamName}'`, function(err, result) {
if (err) {
throw err;
} else {
for (let i = 0; i < members.length; i++) db.query(`INSERT INTO team_user (user, team) VALUES ('${members[i]}' , ${result[0].id_t})`);
}
});
if (message.guild !== null) message.delete();
let newTeam = new Discord.RichEmbed()
.setThumbnail("https://cdn.discordapp.com/emojis/542789472421675028.png?v=1")
.setColor("#15f153")
.addField("New team has been created!", `Team ${teamName} has been created with total of ${members.length} members!\nGood luck!`);
message.channel.send(newTeam);
}
}
});
What have I tried so far:
Checking if result[0].teamname is undefined
Checking if result length is not 0
try-catch statement

if (result[0] && result[0].teamname == teamName)
First of all you need to check if result[0] is not undefined

You need to short-circuit the condition. All this means is you want to first check that result exists before checking properties of result
So for example, your code should look like this:
if (result && result[0] && result[0].teamname == teamName) {
//Do something
}

If result is array with more then one value, then you need to iterate over every one of them, you can use filter array method for this:
var found = result.filter((row) => row.teamname == teamName);
if (found.length) {
}
You can also as #ThomasKleßen mention in comment check if result is not undefined:
var found = result && result.filter((row) => row.teamname == teamName).length;
if (found) {
}

You can always do a default value
if ((result || [{}])[0].teamname == teamName)
If the result is falsy, it will default to an array of an empty object, which will allow for the array access and dot notation to work, but the equality to fail.

Related

Await Async when looping through large json file

The json file is large around 20mb.
I want to wait until a result is returned or the entire file is looped through, before sending back the age. Currently it returns 0 even if the age is not 0
const app = express()
const genesis = require('./people.json');
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'application/json');
let age = getAge(req.query.name)
res.json({
“name”: req.query.name,
“age”: age, // this is always 0
});
});
function getAge(name) {
genesis.balances.forEach(element => {
if (element.name == name) {
// console here shows correct age
return element.person[0].age;
}
});
return 0;
}
app.listen(3000)
As I said in the comment, the problem was in your getAge method, it was always returning 0.
The return inside the forEach doesn't return the value off of the loop.
Please have a look at the following approach
function getAge(name) {
const person = genesis.balances.find((elm)=> elm.name === name);
return person ? person.age : 0;
}
See code comment below
function getAge(name) {
genesis.balances.forEach(element => { // forEach doesn't return anything
if (element.name == name) {
// console here shows correct age
return element.person[0].age;
}
});
return 0;
}
You probably want instead something like:
function getAge(name) {
const res = genesis.balances.filter(element => element.name == name);
if (res.length === 0) return 0; // not found
return res[0].person[0].age;
}
read more about forEach
Comment: having a person-array under element with "name" is a weird choice, why should a single person-name be mapped to multiple persons?

How to use Array contains in two different array fields in firebase for flutter

I have a document with two fields, searchkeys1 and searchkeys2, I want my firebase query to check if a value I provided is present in searchkey1 and return, if not search searchkey2, my first attempt was to create a query with the value and first check searchkey1 and if the documents returned are empty, try searchkey2, my problem is I keep getting an error when I am trying to check if any documents were returned
"the getter 'documents' isn't defined for the type 'Stream<QuerySnapshot>' "
here is my code
startSearch(input) {
var docSnapshot = FirebaseFirestore.instance
.collection('items')
.where('searchkeys1', arrayContains: input.toString()).snapshots();
if (docSnapshot.documents.length == 0) {
var docSnapshot2 = FirebaseFirestore.instance
.collection('items')
.where('searchkeys2', arrayContains: input.toString()).snapshots();
return docSnapshot2;
} else if (docSnapshot.documents.length != 0) {
return docSnapshot;
}
You need to make your function async and use get insted of smnapshots:
startSearch(input) async {
var docSnapshot = await FirebaseFirestore.instance
.collection('items')
.where('searchkeys1', arrayContains: input.toString()).get();
if (docSnapshot.documents.length == 0) {
var docSnapshot2 = await FirebaseFirestore.instance
.collection('items')
.where('searchkeys2', arrayContains: input.toString()).get();
return docSnapshot2;
} else if (docSnapshot.documents.length != 0) {
return docSnapshot;
}
With get you get the data once as you want it. But with snapshots you get a listener for realtime chanegs.

Else statement executes even if the If statement conditions are valid

I am using Google Cloud function to validate my OTP Authentication, and also using Firebase database to save code in the database.
My problem is, even when the If statements condition are satisfied, it always executes else statement. I am comparing code and codeValid from firebase database with the user input. Thus, my user input is satisfied with code and codevalid is also satisfied, but it always moves to else statement. I dont know why.
Here is my code
const admin = require('firebase-admin');
module.exports = function(req, res) {
if(!req.body.phone || !req.body.code) {
return res.status(422).send({error: 'Phone and Code Must be
Provided'});
}
const phone = String(req.body.phone).replace(/[^\d]/g, '');
const code = parseInt(req.body.code);
return admin.auth().getUser(phone)
.then(() => {
const ref = admin.database().ref('users/'+ phone);
return ref.on('value', snapshot => {
ref.off();
const user = snapshot.val();
if (user.code === code && user.codeValid === true) {
ref.update({ codeValid: false });
admin.auth().createCustomToken(phone)
.then(token => res.send({ token: token }))
.catch((err)=> res.status(422).send({ error:err }));
}
else {
return res.status(422).send({ error: 'Code Not Valid' });
}
});
})
.catch((err)=> res.status(422).send({ error:err }) )
}
So, I always get "code not valid" what ever the input i give. I cross checked all the values with firebase database also, everything matches. But couldn't find why its happening.
Add this above your if condition and check whether your statements are really true. I think it's possible that your datatypes are different for example for user.code and code. So you should also test it with == or with parsing your values.
// values and datatypes are equal
if (user.code === code) {
console.log('user.code === code');
}
// values and datatypes are equal
if (user.codeValid === true) {
console.log('user.codeValid === codeValid');
}
// values are equal
if (user.code == code) {
console.log('user.code == code');
}
// values are equal
if (user.codeValid == true) {
console.log('user.codeValid == codeValid');
}
For more information about the difference of == and === look at this answer:
Difference between == and === in JavaScript

Google App Script - Function Returning Undefined

I'm trying to call a function that gets a channel ID when given a Slack Workspace and channel name. I can get the correct result within the function, but when I try to call the function elsewhere, it is returning undefined.
Function to get the channel ID `
//GET CHANNEL ID FROM LIST OF ALL CHANNELS IN WORKSPACE
function getChannelID(workspaceName, pageLimit, channelName, nextCursor){
var channelListResponseURL = 'https://slack.com/api/conversations.list';
var payload = {
'limit': pageLimit,
'types': 'public_channel, private_channel',
'cursor' : nextCursor
};
var options = createURLargs(workspaceName, payload);
var channelListResponse = UrlFetchApp.fetch(channelListResponseURL, options);
var channelListJson = channelListResponse.getContentText();
var channelListData = JSON.parse(channelListJson);
//iterate through each channel in the returned JSON object and sets the channel ID for the one matching the channelName
for (var i in channelListData.channels){
if(channelListData.channels[i].name == channelName){
var channelID = channelListData.channels[i].id;
Logger.log('FOUND CHANNEL ID: '+ channelID);
return channelID;// IF CHANNEL ID FOUND, THEN EXIT getChannelID FUNCTION AND RETURN CHANNEL ID
}
}
// IF NO CHANNEL ID IS FOUND, THEN CHECK TO SEE IF PAGINATION IS IN EFFECT, UPDATE CURSOR, AND RERUN getChannelID FUNCTION
if (channelListData.response_metadata.next_cursor && channelListData.response_metadata.next_cursor != ""){
nextCursor = channelListData.response_metadata.next_cursor;
getChannelID(workspaceName, pageLimit, channelName, nextCursor);
} else {
// IF CHANNEL PAGINATION IS NOT IN EFFECT, OR REACHED LAST PAGE AND NO RESULT IS FOUND
return 'No Channel Found in Workspace';
}
}
`
I can clearly see the 'FOUND CHANNEL ID: CXXXXXX' string in the logger, so I'm sure it finds it properly.
But when I call this getChannelID from the main function, it is returning undefined.
var channelID = getChannelID(workspaceName, pagLimit, channelName, nextCursor);
Logger.log(channelID);
The weird thing is this seems to work when the JSON object from Slack isn't paginated, but when the results are returned paginated, I just seem to get undefined.
Any ideas why the result it's returning is undefined, even though it works in the function?
I think that in your recursive function, the value is not returned. So how about this modification?
From :
if (channelListData.response_metadata.next_cursor && channelListData.response_metadata.next_cursor != ""){
nextCursor = channelListData.response_metadata.next_cursor;
getChannelID(workspaceName, pageLimit, channelName, nextCursor);
} else {
// IF CHANNEL PAGINATION IS NOT IN EFFECT, OR REACHED LAST PAGE AND NO RESULT IS FOUND
return 'No Channel Found in Workspace';
}
To :
if (channelListData.response_metadata.next_cursor && channelListData.response_metadata.next_cursor != ""){
nextCursor = channelListData.response_metadata.next_cursor;
return getChannelID(workspaceName, pageLimit, channelName, nextCursor); // Modified
} else {
// IF CHANNEL PAGINATION IS NOT IN EFFECT, OR REACHED LAST PAGE AND NO RESULT IS FOUND
return 'No Channel Found in Workspace';
}
Note :
When channelListData.response_metadata.next_cursor && channelListData.response_metadata.next_cursor != "" is true, no value is returned. So I added return.
If this didn't work yet, please tell me. I would like to modify it.
Added :
In my understanding, when the recursive function is run, the process returns to the line which was run. In order to confirm this, I prepared 3 sample functions.
Function 1
function foo1(value) {
if (value == "") {
foo1("bar");
} else {
return "ok";
}
}
Function 2
function foo2(value) {
if (value == "") {
return foo2("bar");
} else {
return "ok";
}
}
Function 3
function foo3(value) {
if (value == "") {
foo3("bar");
}
return "ok";
}
When these functions is run by as follows,
var res1 = foo1("");
var res2 = foo2("");
var res3 = foo3("");
res1, res2 and res3 are undefined, ok and ok, respectively.

Error handler is working in every situation

Handler is working with my code but it shouldn't alert when the the value is not null. I got an alert in either situations. I don't know what went wrong .
var data = {};
var deviceId = ["asdfa23", "asdfa32"]
data[deviceId] = "asdfasdf";
try {
if(data[deviceId].value == null)
throw "this is null"
}
catch(err) {
alert(err)
}
Just replace your in your if statements :
(data[deviceId].value == null)
by :
(data[deviceId] == null)
You don't have value field, it is not an object.
You can do .some() method to check a condition over an array.
var data = {};
var deviceId = "thermoment123";
data[deviceId] = ["er213", "er243"];
for(var device in data){
try{
var bool = data[deviceId].some(function(elm){
return elm
? true
: false
});
if (!bool){
var errorSensor = "The sensor "+ deviceId + " has no data"
throw errorSensor;
}
} catch(err){
alert(err)
}
}
You assign an array to data[deviceId].
The array has two properties 0 and 1 (along with all the inherited properties like forEach and length).
value is not a property of normal arrays and you haven't added one.
you have a couple syntax errors in your code:
var data = {};
var deviceId = "thermoment123";
data[deviceId] = ["er213", "er243"];
for (var device in data) {
try {
if (data[deviceId] == null) { //removed the .value
var errorSensor = "The sensor " + data[deviceId] + " has no data"; //added ';'
throw errorSensor;
} //close brackets that start at from if statement
} catch (err) {
alert(err); //added ';'
}
}

Categories