Nicholas Corin
Nicholas Corin

Reputation: 2404

Delete operator not working in Javascript

This is a function that removes sensitive information from a JSON object before it gets returned to the client. The data that's being passed into the function would either be a JSON object or an array of JSON objects. Why would this function not work?

I know that there are other solutions to the problem, but this is annoying my brain.

I have logged plenty of information in this function and even though JavaScript is asynchronous the functions are running in the order that they should - the recursion is finishing before the final return statement is hit.

The issue right now is that even though everything seems to be working and the delete operator is returning true, the attributes being deleted are still present when the function finally returns.

Example data which is being fetched from MongoDB:

[
    {
        'id': '1',
        'name': 'John',
        'password': 'test123',
        'emailAddress': '[email protected]',
        'emailAddressVerificationCode': 'A897D'
    },
    {
        'id': '2',
        'name': 'Andrew',
        'password': 'test123',
        'emailAddress': '[email protected]',
        'emailAddressVerificationCode': '90H8D'
    },
    {
        'id': '3',
        'name': 'Matthew',
        'password': 'test123',
        'emailAddress': '[email protected]',
        'emailAddressVerificationCode': '56C7C'
    }
]

Any thoughts would be appreciated.

UserService.cleanJSON = (data) => {

    if (Array.isArray(data)) {
        for (let i = 0; i < data.length; i++){
            data[i] = UserService.cleanJSON(data[i]);
        }
    } else {

        if (data.password) delete data.password;
        if (data.emailAddressVerficationCode) delete data.emailAddressVerficationCode;
        if (data.mobileNumberVerificationCode) delete data.mobileNumberVerificationCode;
        if (data.accountType) delete data.accountType;
    }


    return data;
};

Upvotes: 1

Views: 603

Answers (2)

JuanGG
JuanGG

Reputation: 850

You are probably using Mongoose or any other ODM, right? If so, you have to know that you can not change the results unless you call the method .lean() (http://mongoosejs.com/docs/api.html#query_Query-lean).

Mongoose keeps the model safe from any modifications unless you detach the result.

Upvotes: 3

tanwill
tanwill

Reputation: 72

Remove the comma after the last curly bracket in your JSON.

Upvotes: -1

Related Questions