You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Incorrect findByIdAndUpdate Syntax: You were passing req.body.campground as the third parameter (which is reserved for Mongoose options, not request data).
  2. 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].
  3. Not Merging Full Campground Data: Your current code only updates address/lat/lng, ignoring other campground fields from the request.
  4. Default Behavior Returns Old Document: Without the new: true option, findByIdAndUpdate returns 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 request Library: The request package is no longer maintained. Switch to modern alternatives like axios or node-fetch for 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 isSafe middleware isn't blocking the request or modifying req.body unexpectedly.

内容的提问来源于stack exchange,提问作者sounak07

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:08:36