What is the process for removing a property from the prototype within an array of MongoDB objects?

I have a database in MongoDB/Mongoose where I store user information, including passwords. However, when I want to display a list of contacts on the frontend, I don't want to include the passwords for security reasons.

To achieve this, I attempted to remove the password field from each user object before sending the list back to the client:

readAll(req, res, next) {
  User.find()
    .then(users => {
      users.forEach(user => {
        delete user.password;
      });
      res.send(users);
    })
    .catch(next)
},

However, my current implementation is not working as expected. Even though delete user.password returns true, the password field remains untouched due to it being part of the prototype in Mongoose's ModelSchema.

After researching potential solutions on MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete), I tried removing the password property directly from the User prototype like so:

delete User.prototype.password;

Unfortunately, this approach also did not work as intended. So, I'm seeking advice on how to effectively remove the password field from each user object in my scenario. Any help would be greatly appreciated. Thank you!

Answer №1

When working with queries, you have the flexibility to define which fields are included or excluded using projection.

retrieveAll(req, res, next) {
  User.find({}, '-password')
    .then(users => {
      res.send(users);
    })
    .catch(next)
},

Alternatively, you can achieve this by utilizing the Query's select() method.

retrieveAll(req, res, next) {
  User.find().select('-password')
    .then(users => {
      res.send(users);
    })
    .catch(next)
},

Another way to handle this is by modifying the select attribute within the schema configuration itself:

email: { type: String },
password: { 
    type: String, 
    select: false 
},
...

Then, just perform the query as usual:

retrieveAll(req, res, next) {
  User.find()
    .then(users => {
      res.send(users);
    })
    .catch(next)
},

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

Discovering the source DOM element that initiated ng-change

I am currently working with angularJS and have multiple <select> elements on my webpage, each with its own ng-change function. Here is an example: <select id="hairColorComponent" ng-model="hairColor" ng-options="option.name for option in ...

Issues arise when attempting to determine the accurate dimensions of a canvas

Looking at my canvas element: <canvas id='arena'></canvas> This Element is set to fill the entire website window. It's contained within a div Element, both of which are set to 100% size. I attempted running this script: var c ...

Find the position of an element in an array that includes a specific string value using JavaScript or Node.js

I need help figuring out how to find the index of an array that contains or includes a specific string value. Take a look at my code below to see what I've tried so far: Here is a simple example: var myarr = ["I", "like", "turtles"]; var arraycontai ...

Error in Sequelize database: Column name does not exist in the database

The issue at hand involves a findAll product selector with a column labeled "PermissionId" that does not actually exist. I am puzzled as to why Sequelize is generating this non-existent column. The errors encountered are as follows: Unhandled rejectio ...

Discovering the art of importing JavaScript files dynamically within controllers

I have one main form through which I pass data from 10 different components, each including the ID of a table that I need to retrieve data from in the database. The issue I am facing is that the code responsible for fetching this data asynchronously is spr ...

Unable to activate function when closing Vuetify v-alert

Is there a way to trigger a function when the Vuetify v-alert is closed? I have explored the documentation but haven't found any information on this specific functionality. In the codepen example, the dismissible attribute allows for closing the alert ...

What is the best way to increase the values of all elements in an array within the specified range in MongoDB?

If I have this specific data in a MongoDB document: { "_id" : 1, "seats" : [ 80, 85, 90, 95 ] } { "_id" : 2, "seats" : [ 88, 90, 92, 97 ] }, { "_id" : 3, "seats" : [ 85, 100, 90, 85 ] }, I am looking to update the seats array of position 1 to position 3 ...

What is the url of the file at input.files[i]?

I've encountered an issue with my JavaScript code. Currently, when a user uploads a file, the code grabs the file name. However, I need it to fetch the file's URL on the user's PC instead. How can I implement this? This is my code snippet: ...

Loading animation reminiscent of a whirlpool, similar to the movement

In my quest for the perfect animation, I have scoured far and wide. Unfortunately, the one I found at http://jsfiddle.net/pedox/yed68/embedded/result/ is created using css, which many browsers do not yet support fully. I also explored , but found it to be ...

Executing jQuery post request on a div loaded via ajax

I'm facing a challenge with my webpage. I have a section where the content of a div is loaded via ajax. This div contains forms, and after submission, it should update to display the new content without refreshing the entire page. Can anyone guide me ...

A guide on seamlessly transitioning from a mobile website to the corresponding native app

I am currently working on a mobile website project. This website is built using basic HTML and is accessed through a URL on a web browser, not as a native app or through PhoneGap. The client has requested links to their Facebook, Pinterest, YouTube, Twitt ...

How can I incorporate a fade opacity effect into my Div scrolling feature?

I successfully implemented code to make div elements stick at the top with a 64px offset when scrolling. Now, I am trying to also make the opacity of these divs fade to 0 as they scroll. I am struggling to figure out how to achieve this effect. Below is ...

Guide to transferring existing Mongoose Schema information to updated Mongoose Schema Data

In the schema I was using previously with Mongoose, it looked like this: social:{ instagram: String, facebook: String, whatsapp: String, } Now, my updated Mongoose Schema is structured differently: social:{ instagram: { dat ...

Enhance multiple select functionality

I am currently working on a function to dynamically update the options in a select input based on the selection made in another select input. Specifically, when Method1 is selected, I want only the options 1A, 1B, and 1C to appear in the second select. S ...

Is it acceptable to use $nin in the db.collection.find() function?

Currently, I am utilizing the mongodb shell and experimenting with conducting a collection query within another collection query. I want to confirm if the following query is valid: db.watchers.find( { login: { "$nin": [db.results.find()] } } ) My main go ...

Dimming the background of my page as the Loader makes its grand entrance

Currently, I am in the process of developing a filtering system for my content. The setup involves displaying a loader in the center of the screen whenever a filter option is clicked, followed by sorting and displaying the results using JQuery. I have a v ...

"Utilizing Date Labels on the X-axis in Google Chart API: A Step-by-Step

Is it possible to create a chart using Google Chart API where the X-axis values represent the days in a month? I have a set of data points that are not evenly distributed. For example: Date - Value 1/1/2009 - 100 1/5/2009 - 150 1/6/2009 - 165 1/13/2009 - ...

Unable to display data retrieved from JSON file

I am encountering an unusual issue while trying to retrieve elements from JSON in JavaScript. I fetch a JSON string from a URL using the following code: // Create Request HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"www.someurl ...

Using Ajax script to transfer user information to a php file in order to refresh the modified row in a table

Recently, I created a table in PHP to display certain data. Here's how it looks: <?php echo '<table id="tableteste" class="table table-striped" width="100%">'; echo '<thead><tr>'; echo &apos ...

How do I fix the build error that says "Operator '+' cannot be used with types 'number[]'?

The function below is designed to generate unique uuidv4 strings. function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => ( c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)) ...