1

I have the following code and at the end of the block there is an if statement, but even though it is false, the code after still runs and the data gets added to MongoDB. I don't understand why...

When i test it by sending a get request with insomnia, the items get added to MongoDB.

const router = require('express').Router();
const xml2js = require('xml2js');
const Avaya = require('../../models/avayaLogs')

router.route('/').get(async (req, res) => {

    const axios = require("axios");
    const getData = axios( {
        url: "http://127.0.0.1:60000/onexagent/api/nextnotification?clientid=65e814f0-e7d8-4404-b9e5-203bfc7935c5",
    })

    const data = await getData;
    const converted = xml2js.parseStringPromise(data.data, { mergeAttrs: true })
    .then(result => result);
    const logs = await converted;
    const notifType = []
    const notifDetails = []


    for (let i in logs.NextNotificationResponse) {
        notifType.push(i)
    }

    for (let i in logs.NextNotificationResponse[notifType[1]][0])
    {notifDetails.push(i)}

    const arranged = {
        NotificationType: notifType[1],
        ResponseCode: logs.NextNotificationResponse[notifType[0]][0]
    }

    for (let i = 0; i < notifDetails.length; i++)
        {
        arranged[[notifDetails[i]][0]]= logs.NextNotificationResponse[notifType[1]][0][notifDetails[i]][0]
        }
        console.log(arranged)




    if (arranged.NotificationType === 'VoiceInteractionCreated' || 'VoiceInteractionMissed' || 'VoiceInteractionTerminated') {
        const newLogs = new Avaya({
            notification: arranged

        });

        newLogs.save()
        .then(logs => res.json(logs))
        .catch(err => console.error(err));
    }


});

module.exports = router;
Adrian Sultu
  • 330
  • 5
  • 16
  • 2
    `(arranged.NotificationType === 'VoiceInteractionCreated' || 'VoiceInteractionMissed' || 'VoiceInteractionTerminated'` is not a valid way to check against multiple values. It's always going to be true – VLAZ Jun 08 '20 at 13:22
  • 1
    'Foo' || 'Bar' is always true. – Josu Goñi Jun 08 '20 at 13:23

2 Answers2

2

You should compare them individually:

if (arranged.NotificationType === 'VoiceInteractionCreated' || arranged.NotificationType === 'VoiceInteractionMissed' || arranged.NotificationType === 'VoiceInteractionTerminated') 
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1
if ((arranged.NotificationType === 'VoiceInteractionCreated') || 'VoiceInteractionMissed' || 'VoiceInteractionTerminated') {

In the above code I added some brackets the show you why it will return true. Strings are considered Truthy in Javascript.

This should give you the desired output.

if (arranged.NotificationType === 'VoiceInteractionCreated' || arranged.NotificationType === 'VoiceInteractionMissed' || arranged.NotificationType === 'VoiceInteractionTerminated') {
stilllearning
  • 163
  • 10