Unable to amend or remove fields within a JSON object

Typically, my process would include the following steps:

var res = {};
res =   {   _id: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5327362027132736202736217d303c3e">[email protected]</a>',
            password: 'ABCDEF',
            phone: '123123123',
            name: 'Torben Tester',
            userLog: [ 
                { date: 1510561026, text: 'was CREATED' },
                { date: 1510593431, text: 'was UPDATED' }
            ] 
        }

res.foo = "bar";
delete res.password
delete res.userLog

After these operations, the resulting object would be as follows:

{   _id: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aedacbdddaeedacbdddacbdc80cdc1c3">[email protected]</a>',
    phone: '123123123',
    name: 'Torben Tester',
    foo: 'bar'
}

However, when retrieving the record from MongoDB

usersTable.findOne (
    { _id: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="592d3c2a2d192d3c2a2d3c2b773a3634">[email protected]</a>' }
,function (err, data) {
    res = data
}

The variable res remains unchanged after this operation

Any attempts to modify it afterwards, such as:

res.foo = "bar";
delete res.password
delete res.userLog

Lead to no visible changes. There are no errors and res retains its original form.

I am puzzled by this behavior. Could it be that res has a different nature when retrieved from mongodb? (It is not an array, as I have verified)

Even upon logging res, its structure appears identical in both scenarios.

If you have any insights or suggestions, they would be greatly appreciated. I have been stuck on this issue for quite some time.

To provide further clarity, here is the actual code snippet:

usersTable.findOne (
    { _id: userID }
,function (err, data) {

    show("============BEFORE================")
    show({data})
    data.agentName = agentName + "XXXX";
    delete data.password
    delete data.userLog
    show("============AFTER================")
    show({data})

    return resolve(data);
}   

Answer №1

Here's how I tackled the issue:

data = data.toJSON();

And that was all it took for everything to fall into place.

So, don't be deceived by the output of console.log(data) because it will look identical regardless of whether your result is a valid Json object or not.

It's just unfortunate that there were no error messages indicating that "This is not a json object" or something along those lines.

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

What is the best way to extract data from a proxy in VUE3?

Currently, I am utilizing the ref() function to store data retrieved from Firebase. However, when attempting to filter and retrieve a single record, the outcome is not as expected. Instead of returning a single object, something different is being displaye ...

Modify the contents of a textbox by editing the text as you type

Text within the text box follows this format: login -u username -p password When entering this text, I want to substitute 'password' with a series of '*'s equal in length. For example: 'login -u <a href="/cdn-cgi/l/email-prot ...

Converting a CSV string into an array only when there is a line break in the body

Need help to convert a CSV string into an array of array of objects. Struggling with handling \n in the incoming request, causing issues with splitting and code errors. The string format includes messages enclosed in ". "id,urn,title,body,ri ...

Discovering a way to extract all information from a JSON POST request using curl

Exploring the open data project on spogo.co.uk (Sport England) has been quite engaging. For a search example, check out: https://spogo.co.uk/search#all/Football Pitch/near-london/range-5. I've been experimenting with Cygwin and CURL to POST JSON dat ...

Whenever I relocate the button's position within the Bootstrap framework, it seems to end up in a completely different

body <div class="container" style="margin-top: 70px;"> <div class="formlogin bg-light bg-gradient shadow-lg p-3 mb-5 bg-body rounded col-8"> <p id="signText"> Signin Fo ...

Python Pandas allows for easy conversion of DataFrames to JSON with multiple levels

Could someone assist me in converting a pandas dataframe into a JSON format with distinct levels? Here is an example dataframe: df = pd.DataFrame([ {"type":"Feature","Id":319,"Departament":"1 DE MAYO","State":"CHACO","coordinates":[[[-58.9537 ...

Creating Projects Without a Build System in Sublime Text 3

I'm having trouble getting the sublime build system to function properly. When attempting to run my code, I receive a "No Build System" error message. I have already set the build system to Automatic under Tools->Build Systems and saved the file a ...

Attempting to enhance the modularity and readability of my code

Looking for assistance to enhance the modularity and readability of this lengthy code. Any tips on how to simplify it and improve clarity would be greatly appreciated! I'm currently working on a street fighter game, and here's what I have so far ...

Implementing Node Express 4 to efficiently handle response generation from successive API requests

I'm currently in the process of developing a NodeJS server using Express4. The main purpose of this server is to act as a mediator between my frontend Angular app and a 3rd party API. I've set up a specific path that my frontend app can request, ...

When attempting to insert a new object in Laravel, the JSON file gets completely replaced

I have a scenario where I need to add a JSON object to an existing JSON file (located in the `storage/app` folder). However, every time I do this, it ends up replacing all the previous data. The code snippet from my controller is as follows: public funct ...

Issues with decoding JSON data in PHP

Struggling to assign a JSON Object to a PHP Variable? When attempting to use var_dump, it's showing NULL. Here is the PHP code: <?php $json = utf8_encode(file_get_contents('http://socialclub.rockstargames.com/ajax/stat/1/profile_body/sta1/ ...

Is there a way to access the value variable from a JavaScript file located in the javascript folder and bring it to the routes/index.js file in a Node.js and Express application?

I'm currently working on transferring the input value from an HTML search box to the index route file in Node.js using Express. I have successfully retrieved the value from the search box in the javascript/javascript.js file, and now my objective is t ...

I possess a JSON object retrieved from Drafter, and my sole interest lies in extracting the schema from it

Working with node to utilize drafter for generating a json schema for an application brings about too much unnecessary output from drafter. The generated json is extensive, but I only require a small portion of it. Here is the full output: { "element": ...

Trigger a jQuery click event to open a new tab

On a public view of my site, there is a specific link that can only be accessed by authenticated users. When an anonymous user clicks on this link, they are prompted to log in through a popup modal. To keep track of the clicked link, I store its ID and inc ...

Developing play and pause capabilities using JavaScript for the existing audio player

Currently, I am developing a Chrome extension that includes an HTML popup with buttons to play audio files. However, I feel that my current approach is not the most efficient and I am struggling to find ways to simplify the process. The method I am using n ...

Showing content from a JavaScript variable once a button has been clicked

Imagine you are using express.js and have a JavaScript variable embedded in an ejs file like this: <%= someVariable %> How can you display the value from this variable on the same page, for instance within a bootstrap modal element (check out https: ...

Utilizing User Designations in Firebase's Real-Time Database

After importing a JSON file containing example Users into the Realtime Database, a minor issue has been identified. As each User is added, they are automatically sorted based on their order in the JSON File. Consequently, starting with User 4 assigns them ...

In the event that the API server is offline, what is the most effective way to notify users that the server is not accessible on the client-side?

I am working on a project where my website interacts with an API hosted on a different server. The website makes API calls and displays the data in a table. However, I want to implement a way to alert the user client-side using JavaScript if the API server ...

Ways to verify if the scroll bar of a user is not visible

Is there a method to detect if the user has forcibly hidden the scroll bar in the operating system? 1. Automatically based on mouse or trackpad 2. Always 3. When scrolling I want to adjust the width of an HTML element if the scroll bar is visible, which c ...

python Unable to convert list to JSON

Issue I am facing a problem with converting the results of a REDIS db query to JSON data. The query returns a SET of byte strings, which I then convert to a LIST of regular strings. Now, I need to find a way to convert this list to JSON in order to retur ...