eliminating attributes from a JavaScript object

Seeking a method to strip object properties before sending them to the front-end.
Why does this code work as intended:

var obj = {
    name: 'cris',
    age: 22,
}
console.log(obj) //displays name and age
delete obj.name
console.log(obj) //displays age

while this one does not:

User.findOne({ username: req.query.username }, function (err, user) {
    if (user != null) {
        console.log(user) //displays all properties
        delete user.salt || delete user['salt']
        console.log(user) //displays all properties
    } 
});

Answer №1

user in this context is a Mongoose document, not just a standard object.

If you want to convert it into a regular object, you can do so by using the toObject() method:

user = user.toObject();

Answer №2

When using the delete function, it is necessary to first convert the model document into a plain JavaScript object by utilizing the toObject method:

User.findOne({ username: req.query.username }, function (err, user) {
    if (user != null) {
        console.log(user) //output all properties
        user = user.toObject();
        delete user.salt || delete user['salt']
        console.log(user) //remove salt property
    } 
});

Additionally, another way to modify and eliminate specific keys is demonstrated below:

User.findOne({}, function(err, user){
  user.key_to_delete = undefined;
  user.save();
});

Answer №3

Instead of a plain JS object, Mongoose returns an instance of the model. To access the data you need, use user.toObject().

Answer №4

When utilizing the db.collection.findOne() method, keep in mind that it will provide a cursor. To properly handle this data, you should convert it into an object using the toObject() function. Once converted, utilize user.toObject(), and proceed by deleting the unnecessary elements before sending it over to the client.

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

Creating Apache Arrow vectors in TypeScript for writing data to a Table

Currently, I am in the process of creating a method that is designed to take a column of data, referred to as data: any[], and then pack it into an Arrow-typed Array Buffer for insertion into an Arrow table. To illustrate with an example, if we consider T ...

JavaScript: utilizing 'this' and onClick events

Recently, I created a basic slideshow with 4 images where upon clicking, the selected image displays in a larger div box. The functionality is quite straightforward, but if you have any queries, feel free to ask. As of now, with only 4 images in the slides ...

Numerous CSS/JS Dropdown Menus

I am seeking the ability to implement a dropdown through CSS in various locations within my HTML prototype. This implies that I require the capability to position multiple dropdowns anywhere on the page. Currently, I utilize this method to generate a sing ...

Using v-model with an input file is not supported

Is there a solution for not being able to use v-model in an input tag with type="file"? Here is an example of the HTML code causing this issue: <input v-model="imageReference" type="file" name="file"/> ...

Is it necessary to decode the JSON data stored in the variable?

Consider the code snippet below: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var responses = JSON.parse(this.responseText); var ...

Prevent parent from scrolling when hovering over a div in HTML5

Unfortunately, the scrolling attribute is not supported in HTML5. I'm facing an issue where I have an svg inside an iframe within a div, and I need to enable scroll functionality within the div while preventing the page from scrolling at the same time ...

Does anyone know of a CSS/JavaScript framework that can be used to replicate the look and functionality of the iOS home

I'm wondering if there is a CSS/JavaScript framework that replicates the layout of an iOS home screen. I want to create a kiosk website with a grid layout similar to Android/iOS where apps can be displayed as icons. ...

Return true in an incorrect manner

Coderbyte Challenge 7 Need help with a function that checks if every letter in the string is bounded by '+' signs. The code provided seems to be returning incorrect results - it should return false for the input string below as 'k' is ...

What is the process of directly accessing JSON objects using their own object reference?

Consider the json files below: const obj1 = { en: { user: { name: "John" } }, language: "en" } const obj2 = { ru: { user: { name: "Vladimir" } }, language: "r ...

Arranging titles on the top of the page in a column format, resembling an index

Has anyone figured out how to make the title of the content stick at the top, one below the other, as the user scrolls? I've been using Bootstrap's Scrollspy, which works fine, but I need a few additional features. You can check out the codepen l ...

What is the best way to recursively analyze JSON and locate a particular object?

Check out my JSON file here! Below are the C# classes generated from the JSON: public class SiteNode { public string url; public string[] param; public string serviceid; public bool is_enabled; public string icon; public string no ...

Search for a specific key within a list of dictionaries

I am working with an array of dictionaries: arrayDict: [ { Description: "Dict 0" Category: [ 'First', 'Both', ], }, { Description: ...

An error has been detected by Internet Explorer 8 at line number 373402504

Internet Explorer 8 is throwing an error message that seems to be from a different galaxy ("Expected identifier, string or number") at a line number that makes no sense. Surprisingly, the code functions perfectly on FireFox. Checking the source code, I se ...

Attempting to understand how to retrieve specific items from my MongoDB Database that are associated with a particular user based on their ID

I've been attempting to retrieve specific items (Portfolio pics) that have been submitted by a user from my Mongo Database. However, when I checked the extracted items using Console logs, it seems to display all portfolio pieces for every user instead ...

What is the best way to update a JSON file using a bash script with jq: utilizing heredocs or key assignments?

Here is a snippet from my JSON file, although the full file is longer. { "anomalyDetection": { "loadingTimeThresholds": { "enabled": false, "thresholds": [] }, &quo ...

Issues arise with the functionality of CSS and JavaScript after successfully deploying a Next.js and React project to the server side

I need to deploy my React+Next and Node.js projects on the same port. To achieve this, I converted my TypeScript files to JavaScript and moved the .next folder to the backend side. Now, my API and frontend code are functioning on the same port thanks to Ex ...

Troubleshooting issues with injecting MongoDB connection in NestJS as it fails to function

I am attempting to establish a basic connection with my localhost: Instead of using Models or Schemas due to the dynamic nature of the data structure, I prefer to work with the native Mongoose Connection app.module.ts import { Module } from '@nestjs ...

Exploring Mongoose Documentation for Winston Logging

After switching to Winston for logging, I encountered an issue with logging mongoose documents after an exec call. Here is an example: Model.find().exec(function (err, docs) { console.log(docs) // This prints the collection correctly winston.info ...

How can I adjust the vertical position of Material-UI Popper element using the popper.js library?

https://i.stack.imgur.com/ZUYa4.png Utilizing a material-ui (v 4.9.5) Popper for a pop-out menu similar to the one shown above has been my recent project. The anchorElement is set as the chosen ListItem on the left side. My goal is to have the Popper alig ...

Guide on showcasing all entries in the database within the body section of an HTML table

Looking to showcase data from a table inside the body section of an html page This is the code I've been working on: <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="vi ...