Mongoose数据无法更新:Node.js调用Google Maps API更新经纬度失败
Fixing Your Node.js PUT Route for Google Maps Geocoding Updates
Let's walk through the issues in your code and fix them step by step:
Key Issues Identified
- Incorrect
findByIdAndUpdateSyntax: You were passingreq.body.campgroundas the third parameter (which is reserved for Mongoose options, not request data). - Missing Error Handling for Invalid Addresses: If the Google Maps API returns no results (invalid address), your code would crash when trying to access
data.results[0]. - Not Merging Full Campground Data: Your current code only updates address/lat/lng, ignoring other campground fields from the request.
- Default Behavior Returns Old Document: Without the
new: trueoption,findByIdAndUpdatereturns the original document instead of the updated one.
Corrected Code
router.put("/:id", isSafe, function(req, res){ const userAddress = req.body.address; const encodedAddress = encodeURIComponent(userAddress); const geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?key=my_key&address=${encodedAddress}`; request(geocodeUrl, function (err, response, body) { if (err){ console.log('Geocoding API Error:', err); req.flash("error", "Failed to fetch location data"); return res.redirect("back"); } try { const data = JSON.parse(body); // Handle cases where API returns no results if (!data.results || data.results.length === 0) { req.flash("error", "Invalid address - could not find location"); return res.redirect("back"); } const location = data.results[0].geometry.location; const formattedAddress = data.results[0].formatted_address; // Merge location data with other campground fields from the request const updateFields = { ...req.body.campground, address: formattedAddress, lat: location.lat, lng: location.lng }; // Correct Mongoose findByIdAndUpdate syntax Campground.findByIdAndUpdate( req.params.id, {$set: updateFields}, {new: true}, // Return the updated document instead of the original function(err, updatedCampground){ if(err){ req.flash("error", err.message); return res.redirect("back"); } req.flash("success","Successfully Updated!"); res.redirect("/campgrounds/" + updatedCampground._id); } ); } catch (parseError) { console.log('Error parsing API response:', parseError); req.flash("error", "Failed to process location data"); res.redirect("back"); } }); });
Additional Recommendations
- Replace Deprecated
requestLibrary: Therequestpackage is no longer maintained. Switch to modern alternatives likeaxiosornode-fetchfor more reliable HTTP requests. - Validate API Key: Ensure your Google Maps API key is valid, has the Geocoding API enabled, and isn't restricted incorrectly in the Google Cloud Console.
- Log API Responses: Add
console.log(data)after parsing the API response to verify you're getting the expected structure during debugging. - Check Middleware: Confirm your
isSafemiddleware isn't blocking the request or modifyingreq.bodyunexpectedly.
内容的提问来源于stack exchange,提问作者sounak07
相关产品推荐
相关产品推荐

