Updating the code for Express to store JSON data in a database field

Struggling with setting up my first basic CRUD functionality in Express JS and I can't seem to track down this frustrating bug.

Every time I attempt to update a field, instead of displaying the new data, the JSON from that field is shown on the view.

Here's a snapshot:

Check out the controller gist here: https://gist.github.com/tiansial/2ce28e3c9a25b251ff7c

Answer №1

The functionality of the update method lies in its ability to search for and modify documents without returning the updated documents themselves. Essentially, this means that you can locate documents based on specific criteria without actually making changes to them, as the initial parameter of the update function serves as the search filter. To actually update an existing document with new properties, you would need to utilize the save function.

Below is a modified snippet of your code (not tested):

//PUT request to update a blob by ID
.put(function(req, res) {
    //Locate the document by its unique identifier
    mongoose.model('Email').findById(req.id, function(err, email) {
        //Implement error handling logic
        if (email) {
            // Obtain values from REST or form inputs using their respective "name" attributes
            email.email = req.body.email;
            email.password = req.body.password;
            email.servico = req.body.servico;

            //Save the updated document
            email.save(function(err) {
                if (err) {
                    res.send("An error occurred while updating the information in the database: " + err);
                } 
                else {
                    //For HTML response, redirect back to the original page; alternatively, provide a success message through a new view.
                    res.format({
                        html: function(){
                            res.redirect("/emails");
                        },
                        //For JSON response, display the updated values
                        json: function(){
                            res.json(email);
                        }
                    });
                }
            });
        }
    });
})

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 incorporate a style attribute into my EJS page content?

Having trouble with adding custom style. It seems to work, but there's an error displayed. Apologies for my poor english :( <div class="card card_applicant"> <div class="card_title" style="background-c ...

What is the process of using an if statement in jQuery to verify the existence of a property in a JSON file?

I am working on a task to incorporate an if statement that checks for the existence of a specific property in a JSON file. If the property exists, I need to display its value within HTML tags <div class='titleHolder'> and "<div class=&ap ...

Issue: Node.js Express unable to access static files when the route is nested more than one folder level deep.Resolution

Before we delve into the question, let me share with you the folder structure of my node.js express app: /home server.js index.html /app /routes public.js /public /css main.css In my server.js file, ...

Is it acceptable to replicate another individual's WordPress theme and website design in order to create my own WordPress website that looks identical to theirs?

It may sound shady, but a friend of mine boasts about the security of his WordPress website, claiming it's impossible to copy someone else's layout or theme. However, my limited experience in web development tells me otherwise. I believe it is po ...

CSS background image referencing in React to the public folder's path

I am currently working on a project using Create-React-App and I am trying to set a background image for my header section. Here is how I'm attempting to do it: background-image: url('~/Screenshot_11.png'); However, I encountered an error w ...

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...

What is the best way to load my CSS file using express.static?

How do I properly load my CSS file using express.static in Node.js? I have attempted various methods to link my stylesheet to my HTML file through Express, and I'm also interested in learning how to include images, JavaScript, and other assets to crea ...

fullcalendar adjusting color while being moved

Currently, I have implemented a fullcalendar feature that displays entries for multiple users with different colored calendars. However, there seems to be an issue when dragging an entry to another date - the color reverts back to default. Below is an exa ...

Utilizing Javascript to Extract Data from Twitter Json Files

Can someone provide assistance with parsing JSON feed text retrieved from Twitter? I am looking to access and apply style tags to elements like the link, created date, and other information. Any tips on how I can achieve this task successfully would be g ...

Trouble displaying data in Jquery JSON

I've been on the hunt for hours, trying to pinpoint where the issue lies within my code. Despite scouring different resources and sites, I can't seem to figure it out. Whenever I click "Get JSON Data," nothing seems to display below. Can someone ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

What is the best way to add custom styles to an Ext JS 'tabpanel' xtype using the 'style

Is there a way to change the style of a Ext.tab.Panel element using inline CSS structure like how it's done for a xtype: button element? { xtype: "button", itemId: "imageUploadButton1", text: "Uploader", style: { background : ' ...

Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging! My issue is: When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! ...

Using Node.js and Less to dynamically select a stylesheet source depending on the subdomain

Currently, my tech stack consists of nodejs, express, jade, and less. I have set up routing to different subdomains (for example: college1.domain.com, college2.domain.com). Each college has its own unique stylesheet. I am looking for a way to selectively ...

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...

Unlocking the power of setting dynamic meta content

When using EJS for templating in my node.js webserver, everything has been running smoothly except for one issue. After integrating the head file into a page, I encountered the following error: SyntaxError: Unexpected identifier in /home/runner/superstrap/ ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...

How can I incorporate Bootstrap/Semantic UI into an Express project without relying on external CDNs

After downloading the minified version of Bootstrap and placing it in the root directory of my project, I added the following code to a HTML file located in /views/: <link rel="stylesheet" href="/bootstrap.min.css"> Despite this, the page remained ...

I am encountering difficulties displaying the image and CSS files from another folder in my HTML with Node.js

I am facing difficulty in establishing a connection between my front-end and back-end using node.js. As a result, the website only displays the HTML code without linking to the CSS or image files. Here is the folder structure: root -src •pi ...

Having troubles with Navbar svg images not loading on certain pages on the express/ejs app?

Hello there, I'm encountering an issue with my navbar in an express app. The navbar is saved as a partial and included in a boilerplate wrapper used on most pages. Here's a snippet of how it looks: <h1>HELLO<h1> Within the boilerplat ...