What is the process for making changes to a document in Mongoose?

My goal is to allow users to update existing mongoose documents using a form with method-override package. Despite trying various solutions found on Stackoverflow, I have not been able to resolve my issue. The desired functionality is for the user to view their existing document, submit the form with new values, and have it update the database.

I attempted the solution provided in this post How do I update/upsert a document in Mongoose? among others, but it did not work as expected.

Initially, I set up a route to display the individual document:

// EDIT - edit location route
router.get("/location/:id/edit", function(req, res) {
    Location.findById(req.params.id, function(err, foundLocation){
        res.render("./locations/edit", {location: foundLocation});
    });
});

This leads to a landing page with a form to update the information on that document:

<form action="/location/<%= location._id %>?_method=PUT" method="POST">
     <div class="form-group"><input class="form-control" type="text" name="location[name]" ></div>
     <div class="form-group"><input class="form-control" type="text" name="location[image]" value="<%= location.image %>"></div>
      <div class="form-group"><input class="form-control" type="text" name="location[longDescription]" value="<%= location.longDescription %>"></div>
       <div class="form-group"><button class="btn btn-lg btn-primary btn-block">Submit!</button></div>
</form>

The route handling the PUT logic is as follows:

router.put("/location/:id", function(req, res) {
    Location.findByIdAndUpdate(req.params.id, req.body.location, {new: true}, function(err, updatedLocation){
        console.log(req.body.location);
        if(err) {
            console.log(err);
            res.redirect("/search");
        } else {
            console.log(updatedLocation);
            res.redirect("/location/" + req.params.id);
        }
    });
});

Although no errors are being thrown by this route, the document is not getting updated. Upon logging req.body.location, I noticed that it was returning undefined. This could potentially be the root of the issue, but I'm not sure how to rectify it.

@Deda this is what is logged in console.log(req.body)

  'location[image]':
   'https://wekivaisland.com/wp-content/uploads/bartlettimage-4977.jpg',
  'location[longDescription]': 'Edited Long Description' }
{ address:
   { street: '51 SW 11th Street Apt. 1537',
     city: 'Miami',
     state: 'FL',
     zip: '12345',
     country: 'United States' },
  author: { id: 5d081e0afd38374b43ca0c14, username: 'danny' },
  rating: 0,
  _id: 5d08dd702456a30948947c73,
  name: 'Random Place',
  image:
   'https://2.bp.blogspot.com/-yKPXCFHoNhQ/WPOOwjqA3QI/AAAAAAAABmQ/88DcGs-Cp5oXAv6fA6hn3J7NRUlYBaxgwCLcB/s1600/Screen%2BShot%2B2017-04-16%2Bat%2B11.33.00%2BAM.png',
  longDescription: 'Place #2',
  shortDescription: 'Place #2',
  __v: 0 }

The issue was resolved by simply setting bodyParser extended to true.

Previously, it was

app.use(bodyParser.urlencoded({ extended: false }));

By changing it to the following code below, everything worked smoothly.

app.use(bodyParser.urlencoded({ extended: true }));

Answer №1

Would you mind sharing the request you're attempting to send to your API? Also, what debugging tool are you currently using? If req.body.location is not defined, it could certainly cause some issues :)

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 deliver a static site through keystone?

I currently have a website built using Keystone and another one that is completely static. My goal is to combine the static site into the Keystone site. When users visit "/", they should see the static site, but if they navigate to "/resources", they wil ...

Incorporating an express server into the vue-webpack-boilerplate for enhanced functionality

Recently, I got my hands on the vue-webpack-boilerplate from GitHub, and so far, it seems pretty impressive! This is my first time working with webpack and ESlint, so I'm eager to learn more. However, I have a question about integrating an express ba ...

Looking to subtly transition from the current webpage to the next one with a fading effect?

I'm looking to create a smooth transition between web pages on my site by slowly fading out the current page and fading in the next one when a link is clicked. $(document).ready(function() { $('body').css("display","none"); $(&a ...

Error: The schema for model "products" has not been properly registered

A Schema has not been registered for the "products" model, resulting in a MissingSchemaError. To resolve this issue, use mongoose.model(name, schema) function as shown below: Cart // Define cart schema const mongoose = require('mongoose'); const ...

Retrieve the properties of an object

I have a JavaScript program where I retrieve values from a JSON file and store them in an array. However, when I attempt to access the elements of this array, it returns nothing. Below is the function that pushes temperatures: temperatures = [] get_info ...

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

Exploring the wonders of Lightbox when dealing with content loaded via AJAX

Using Bootstrap 5 along with the Lightbox library from , I encountered an issue. The Lightbox feature functions properly on regular page loads, but fails to load on content loaded via AJAX. I attempted to resolve this by implementing the following code: ...

How to retrieve the value from a JSON object when the key is unknown in JavaScript

Here is the JSON file I'm working with: { "status": 200, "msg": "OK", "result": { "files": { "count": 1, "pUnJbKzql0f2": { "name": "How ...

The $.parseJSON function accurately retrieves valid items but also presents an endless stream of undefined

Currently, I am in the process of developing a Flask application that fetches teams from a football league. The teams_list method returns the result of an AJAX request. While the output is correct, it seems to trigger an infinite loop that significantly sl ...

retrieve the path of any module within an npm monorepo

I am working on a project using an NPM monorepo structure which utilizes ECMAScript Modules (ESM): <root> |_package.json |_node_modules/ | |_luxon (1.28.0) |_packages/ |_pack1 | |_node_modules/ | | |_luxon (3.0.1) | |_main.js |_pack2 |_ ...

Removing the unhandledRejection event listener in Node.js Express

In order to manage errors in my Express app that use async/await functionality, I have implemented centralized error handling to ensure appropriate status codes and messages are sent as responses. My current approach is as follows: const handleRejection ...

The userscript is designed to function exclusively on pages originating from the backend, rather than on the frontend in a single-page application

I have a userscript that I use with Greasemonkey/Tampermonkey. It's set to run on facebook.com, where some pages are served from the backend during bootstrapping and others are loaded on the fly in the front-end using HRO, similar to how a Single Pag ...

Node.js, PHP, and the Express framework

I have a project where I need to develop a to-do list and a form that allows users to upload png files using Node.js. Currently, I am using the following packages: { "name": "todo", "version": "0.0.1", "private": true, "dependencies": { "ejs": ...

The Route.get() function in Node.js is expecting a callback function, but instead received an unexpected object of type

Recently, I started coding with nodejs and express. In my file test.js located in the routes folder, I have written the following code: const express = require('express'); const router = new express.Router(); router.get('/test', (req ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

Avoid generating `.d.ts` definition files during the onstorybook build process in a Vite React library project

I am currently developing a component library using react and typescript. I have integrated Vite into my workflow, and every time I build Storybook, the dts plugin is triggered. This has two undesired effects: It generates numerous unnecessary folders an ...

Sending a variable to a function in JavaScript (winJs) from a different function

Greetings! Currently, I am developing a Windows 8 app using Java Script. function fetchFromLiveProvider(currentList, globalList,value) { feedburnerUrl = currentList.url, feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&outpu ...

Issues encountered with jQuery's $.ajax function when communicating with PHP

I am having trouble creating a simple app that displays data from a MySQL database using PHP and jQuery. The issue I am facing is with retrieving the data using jQuery. While my PHP script successfully returns the data without any problems, I am not receiv ...

Why is it possible to import the Vue.js source directly, but not the module itself?

The subsequent HTML code <!DOCTYPE html> <html lang="en"> <body> Greeting shown below: <div id="time"> {{greetings}} </div> <script src='bundle.js'></script& ...