The changes made in Express are not reflecting in the MongoDB database as expected

I'm having trouble with my update function. It's not a database issue because delete works fine.

Here is the code for my Update route:

Can someone please assist me? I've been using console.log to display values in the console, and they all seem correct.

I have already tried logging values during the "update" process.

C:\Personal\Books\Trials>node app.js
Trials is running on port 3000
Success Update
5cc86fa0b5e2143684378877
Jim4
{ _id: 5cc86fa0b5e2143684378877,
  fieldname: 'Jim3',
  fieldtype: 'string',
  fieldinputtype: 'textbox',
  __v: 0 }
app.put("/adminstudy/:id",function(req,res){
    studyfields.findByIdAndUpdate(req.params.id, req.body.fieldname, function(err, returnedstudyfield){
        if(err){
            console.log(err);
            res.redirect("/adminstudy");
        } else {
            console.log("Success Update");
            console.log(req.params.id);
            console.log(req.body.fieldname);
            console.log(returnedstudyfield);
            res.redirect("/adminstudy");
        }
    });
});

Below is the form that submits data to the update route:

            <form action="/adminstudy/<%= editedstudyfield._id %>?_method=PUT" method="POST">
                <div class="form-group">
                    <input class="form-control" type="text" name="fieldname" value="<%= editedstudyfield.fieldname %>">
                </div>
                <div class="form-group">
                    <select name="fieldtype">
                        <option value="string">Text</option>
                        <option value="number">Number</option>
                    </select>
                </div>
                <div class="form-group">
                    <select name="fieldinputtype">
                        <option value="textbox">Text Box</option>
                        <option value="Textarea">Text Area</option>
                      </select>
                </div>
                <div class="form-group">
                    <button class="btn btn-lg btn-block btn-success" type="submit">UPDATE THIS STUDY FIELD</button>
                </div>
            </form>

I expected the update to work, but it doesn't. Any assistance would be greatly appreciated.

Answer №1

Make sure the "update" parameter consists of key-value pairs in the form of an object:

{ fieldname: req.body.fieldname }

(Strangely, no error is thrown even though it lacks proper formatting)

Answer №2

When interacting with MongoDB, ensure that you are sending the correct data format. In this case, it seems like you should send {fieldname: req.body.fieldname}

Consider using the following syntax when updating a document in the studyfields collection: 
studyfields.findByIdAndUpdate(req.params.id, {fieldname: req.body.fieldname} ...

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

How do I access the variable value from inside a function in jQuery?

Is it possible to extract the value from 'a = entry.username' outside of the function? I need to retrieve a value that is already being looped inside the function. $('#btnlogin').click(function(){ var usernamelogin = $(&apos ...

Executing a REST call only when the previous one has successfully completed

Is there a way to execute a second REST request only after multiple successful responses from the first one? I have noticed that while in a normal state these requests are executed sequentially as required, issues arise when dealing with a large number o ...

What is the process for updating the combination selector for each product within a specific category in PrestaShop 1.7?

We have a range of products in a specific category, each offering multiple pack sizes with varying prices (e.g. 1, 3, 5, 10, 25, 50, 100). EDIT: The homepage features these products displayed using an owl-carousel within a div element: https://i.sstatic.n ...

How can I properly retrieve an entry for processing within my route?

Hello everyone! This is my first question on this platform, so please bear with me if I'm missing any important details. I'll add them as soon as possible. I am currently working on setting up a camel route where I retrieve a URL from my Databas ...

Troubleshooting 'Warning: Prop `id` did not match` in react-select

Having an issue with a web app built using ReactJs and NextJs. I implemented the react-select component in a functional component, but now I'm getting this warning in the console: Warning: Prop id did not match. Server: "react-select-7 ...

Why do I continue to encounter the error message saying 'jQuery is not defined'?

As a newcomer to the world of jQuery and Visual Studio Environment, I embarked on the journey of creating a circular navigation menu bar following the instructions provided in this link. Despite my efforts, I encountered a hurdle in the head section where ...

Dividing a string using regex to deal with numerical issues

My task involves processing a list of strings that look like this: Client Potential XSS2Medium Client HTML5 Insecure Storage41Medium Client Potential DOM Open Redirect12Low The goal is to split each string into three parts, like so: ["Client Potential X ...

Why do I keep receiving the unprocessed JSON object instead of the expected partial view output?

Upon submitting my form, instead of displaying the testing alerts I have set up, the page is redirected to a new window where the raw JSON object is shown. My assumption is that this occurrence is related to returning a JSON result from the controller. How ...

I'm having trouble getting my HTML POST request form to connect with the Express app.post. Any tips on how to properly pass on numeric variables to a different POST request?

There seems to be a misunderstanding or error on my part regarding POST and GET requests based on what I've read online. On myNumber.ejs, I have a submit form. Upon submission, the view switches to Add.ejs. The goal is for Add.ejs to display both the ...

Is there an issue with the initial positioning of the tooltip in the seiyria angular-bootstrap slider?

After implementing the Seiyria angular-bootstrap-slider for a range slider, I encountered an issue where the tooltip is positioned incorrectly upon loading the page. While it functions correctly on a regular page, it appears in the wrong position within a ...

Generate a PDF document on the user's device

Is there a way for me to trigger the print command on a PDF file without relying on Adobe PDF viewer's print button? I'm interested in using a separate event instead of the print button within the PDF viewer. Is this achievable? ...

Express Postgres database for a RESTful API

I am currently working on developing a RESTful API using Node and Express. My database of choice is PostgreSQL, and I plan to utilize the pg-promise package for this project. While I understand that I must establish a connection with the database in my ap ...

Ember.js: Data not defined

I am currently working on setting up a basic API Express server that will return JSON data to my Ember.js App. Below is the configuration of my server : var express = require('express'); var mongoose = require('mongoose'); var app = ...

Developing entities in Express.js

My express app is currently fetching data from an external API through the following endpoints: api.com/companies (GET, POST) api.com/companies/id (GET, PUT) To improve maintainability and avoid code repetition, I am looking to create a model for handlin ...

What causes the error "Why am I receiving a "Cannot read property 'length' of undefined" when looping through a pug template?

Currently, I am in the process of developing a project using Node and Express. My objective is to have the home page display signup and login links in the nav bar when the user is not logged in. Initially, everything seemed to be working fine, and I was ab ...

How can I showcase a Google donut chart using an array of data in a React application?

I have created a doughnut chart that is supposed to take an array as data. However, when I input the array, nothing shows up on the chart. How can I create a chart with array data? sum.js ... const arr = []; arr.push({ key: capitalizeEachFirst ...

Leveraging Facebook Graph API in combination with the Express framework

After reading this particular answer, I am struggling to comprehend how to implement it in express. Let's say at the route /fbtest, I want to display information about a Facebook user. The solution proposes making a request to https://graph.facebook.c ...

Post a message utilizing javascript

Can a client-side tweet be generated using JavaScript, a text box, and a submit button? This involves entering the tweet text into the textbox, clicking the button, and then tweeting it with an authenticated account all within the client's browser. ...

Leveraging Iframes for efficient user authentication within an Angular application

Incorporating an Iframe into one of my templates for authentication has presented certain challenges. Case in point: When a user finishes a training session, they must verify their identity by authenticating with a ping identity server that will redirect ...

Enhancing user experience with dynamic search results: JQuery AutoComplete powered by XML

As a newcomer to AJAX, JavaScript, and the web, I'm struggling with understanding this concept. When using JQuery's autocomplete feature with a small flat file of limited items (suggestions.xml), everything works perfectly. However, when switchin ...