Search code examples
pythonmongodbapirest

PUT request with subdocuments


I'm currently creating a PUT request for my backend API to allow users to add restaurants to a dataset. Currently, in the dataset, the lat and lng of the restaurant is under geometry > location. Im unsure how I would specify this in the backend API.

Bellow see how the LNG and lat values are stores in mongodb

Here is what I have for the backend API so far:

    @app.route("/api/v1.0/restaurant", methods = ["POST"])
    
    def add_new_restaurant():
        if "restaurant" in request.form and "city" in request.form:
            new_restaurant = {
                "restaurant": request.form["restaurant"],
                "city": request.form["city"],
                "reviews": []
            }
            new_restaurant_id = restaurants.insert_one(new_restaurant)
            new_restaurant_link = "http://localhost:5000/api/v1.0/restaurants/" \  +          str(new_restaurant_id.inserted_id)
            return make_response( jsonify(  { "url" : new_restaurant_link } ), 201 )


Solution

  • It's a nested object so you can insert it as such. You can represent it in a dict with a geometry key that maps to a dict value, which has a location key that maps to another dict that specifies that lat/long.

    new_restaurant = {
        "restaurant": request.form["restaurant"],
        "city": request.form["city"],
        "reviews": [],
        "geometry": {
            "location": {
                "lat": LAT_VALUE,
                "long": LONG_VALUE
            }
        }
    }