Eliminate JSON data prior to displaying information to the user/strip JavaScript object attributes

I'm facing a dilemma and can't seem to figure out why I'm unable to resolve my issue.

My SPA is created using AngularJS, Node.JS, and MongoDB (Mongoose). On the client side, I have a registration form for new users. The form includes a text input with an associated function triggered by its onblur event (ng-blur to be exact). This function makes an AJAX/$http call to the backend to check if the username is unique before submitting the form. Everything seems to be working fine, here's the code snippet I've been working on (lightly modified for this question)...

Here's the input box,

<input type="text" name="displayName" id="displayName" ng-model="user.displayName" ng-blur="checkUserName(user)" />

And here's the blur function in my controller

this.userNameCheck = function(user){
        return $http({method: 'GET', url: '/api/users/displayName/' + user.displayName})
            .then(function(response) {
               if(response.data.length > 0){
                   user.userWarning = userWarning; // userWarning is a string/ var that is passed to the form
               }

            }, function(response) {
                console.log(response);
            });
    };

Lastly, here is the Node/mongoose code from another project:

exports.displayName = function (req, res, next, displayName) {

    User.find({displayName : displayName}).limit(1).exec(function (err, results) {
        if (err) return next(err);
        if (!results) return next(new Error('No user found'));
        res.jsonp(results || null);
    });

};

Everything seems fine, however, upon checking the console, it appears that when there's a match, the returned results object contains sensitive information like hashed password and salt. To address this, I updated my backend code as follows:

exports.displayName = function (req, res, next, displayName) {

    User.find({displayName : displayName}).limit(1).exec(function (err, results) {
        if (err) return next(err);
        if (!results) return next(new Error('No user found'));

        // Updated code
        if(results.length !== 0){
            var returnObj =  results[0];
             delete returnObj.hashed_password;
             delete returnObj.salt;
             delete returnObj._id;
            res.jsonp([returnObj] || null)
        }else{
            res.jsonp(results || null);
        }
    });

};

However, even after implementing these changes, when making a successful call in Firebug (resulting in a match), the returned object still contains the deleted properties. What am I doing wrong?

Answer №1

In order to remove specific fields from the Mongoose object, you need to avoid manipulating the actual storage directly. A quick fix for this issue would involve:

 let returnData =  results[0].toJSON();
 delete returnData.hashed_password;
 delete returnData.salt;
 delete returnData._id;

An alternative approach is to use the select method (check out the documentation) to choose which fields to include or exclude.

Answer №2

It is possible that the properties in the return object are not actually deleted because they exist further up the prototype chain.

When using the delete operator, if the property is successfully removed from the object, it will be completely erased. However, if a property with the same name is found on the object's prototype chain, the object will inherit that property instead.

~ MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete)

You can verify this by using hasOwnProperty to check, but it might be safer to create a new object with only the desired values, or restrict the returned values directly from Mongo collection?

In JavaScript, you could dynamically create an object like:

var returnObj =  results[0],
safeUserObj = {
   userName : returnObj["username"],
   email : returnObj["email"]
};

res.jsonp([safeUserObj]);

Alternatively, you can filter the fields at the database level by using the aggregation framework's $match and $project (example below, may need adjustments for Mongoose):

db.users.aggregate([
{ $match : { displayName : displayName } },
{ $project : {
    displayName : 1,
    email : 1
  }
}
]);

EDIT: Another approach is to use the project parameter of find to achieve similar results without implementing the aggregation framework.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract information stored in a JSON object and input it into an array

I'm struggling to extract data from a multidimensional array. In my .php file, I retrieve data from a database and encode it to JSON. JSON= {"1":{"SME":"0","SAUDE":"0"}.... Desired data structure: array{ 0 => Array{"SME" => 1, ...

Concealing an element in React

In my code, I have a couple of React classes implemented. When the app is launched, the user sees the following: <div> <h1 className="headings" id="heading"> Football </h1> <input type="text" placeholder="name" /> & ...

Are there any jQuery plugins available that animate elements as the page is scrolled?

Looking for a library that can create entry animations for elements as the page is scrolled? I previously used the animate it library, which was great - lightweight and easy to use. However, it doesn't seem compatible with the latest jQuery version (3 ...

The MongoDB 'find' method is incompatible with DateTime.MinValue

Storing date fields as metadata in GridFS using the Mongo 2.2.3.3 C# driver presents a unique challenge when dealing with DateTime.MinValue. This particular value is represented as Date(-62135596800000), corresponding to the number of milliseconds since Ja ...

Optimizing mongoose schema organization for improved relationships

Currently, I have established 4 models: User, Profile, Interests, and Tokens. There is a one-to-one relationship between User and Profile. User and Tokens have a one-to-many relationship. Additionally, there is a one-to-many relationship between Profile an ...

Converting MongoDB collection to DataFrame object

In a recent inquiry on Stack Overflow, I discussed transforming a DataFrame into a list of dictionaries for uploading to MongoDB. Now, the focus has shifted towards the reverse process. From a MongoDB query, a list of dictionaries containing specific info ...

Is Redux really the new trend in the world of action creators?

I am new to this. I'm a bit unsure, is it okay or silly to use the pattern below? import { createAction, handleActions } from "redux-actions"; const CHANGE_STATE = "appState/CHANGE_STATE"; export const changeState = createAction(CHANGE_STATE, (key, ...

npm ERROR: 404 - The package '@reactivex/rxjs' cannot be found in the npm registry

Encountering problems with the installation of this package through NPM. Attempting to install as it is a dependency of Angular2. Error: npm ERR! Darwin 15.0.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "@reactivex/<a href="/cd ...

What is the alternative name for DOM elements in TypeScript?

When working with a HTMLImageElement, I can simply reference it like this: let image: HTMLImageElement; ... In Dart, importing the dom is possible using: import 'dart:html' as dom; Using 'dom' as an alias for the "dart:html" package. ...

What is the technique for wrapping a component with a rectangle box in ReactJs?

Do you like the design in this example image? I attempted to create a similar layout using Material UI Box, but unfortunately, it only displays the text without rendering the box itself. Take a look at the code I used: import * as React from 'react& ...

Experiencing CORS (Cross-Origin Resource Sharing) issue while utilizing Python Flask-Restful in conjunction with consuming AngularJS (specifically with $

Currently, I am using a Python program in conjunction with the flask-restful extension to provide a restful service. My goal is to consume this service with an AngularJS app. So far, everything is functioning properly on my localhost. However, whenever I m ...

Text index formatting with Pymongo

Trying to set up an index for a text field using pymongo from pymongo import MongoClient mongo_client = MongoClient('localhost', 27017) db = mongo_client["db_name"] The data objects are structured as follows: {'_id': ObjectId('5 ...

Utilizing AJAX and PHP to Showcase Data

Instructions for program flow: 1. When the page loads, the chart will display the total sales from all branches. 2. Upon selecting a specific branch from the dropdown menu, the chart should show the total sales for that particular branch. I am encounterin ...

When contextIsolation is set to true in an Electron application, React components fail to render properly. However, they render without any issues when context

I am currently in the process of learning the react framework and transitioning my electron application from a standard Electron + HTML/CSS setup to incorporate React. However, I have encountered an issue where setting contextIsolation to true for preload. ...

How can mouse clicks be detected using jQuery?

I am looking to dynamically add a class to a link as soon as the user clicks on it, rather than waiting for the mouse click event to be released. Additionally, I want this added class to be removed once the user releases the mouse click. My goal is to repl ...

JavaScript/TypeScript Asynchronous Filtering on AsyncIterable<T>

I am currently working with an AsyncIterable variable and I am trying to apply a filter on it. Take a look at the example below (pseudo code) - class SomeClass { private SOME_CONST= "ABCDE"; private async someFunction(): Promise<strin ...

JavaScript for Acrobat

I am currently creating a form in Adobe Acrobat and incorporating additional functionality using JavaScript. I have been searching for information on the control classes for the form, such as the member variables of a CheckBox, but haven't found any c ...

Enhancing the Appearance of Default Map Markers in Google Maps' Angular Plugin

In my current project, I am working with the 2.0.X version of angular-google-maps. By default, all the markers in the map have the typical Google Maps style (red pointer). However, I want to customize them a bit - either by changing the color while keepin ...

Failure in unit testing MongoDB's WriteOneAsync() when attempting to create a document

I'm facing a bit of a challenge while writing a unit test for testing MongoDB's WriteOneAsync() method. I attempted to run the unit test on a sample MongoDB code that writes a document to the database, but unfortunately, it fails to do so. Here ...

The results of an AJAX file upload operation

Currently, I am utilizing an AJAX File Uploader from the following link: The code I am using is as follows: function ajaxFileUpload() { $('input[type=file]').each(function () { if ($(this).val() == "") { return true; ...