POST request to a nested query – python API

Question:

So i’ve began to create a comment section for users to leave comments under posted events. I’m now trying to set up replies to comments under an event and am having issues. With the code I have, a new link is being generated but it isn’t updating the dataset. Can anyone spot what I’ve done wrong?

@app.route("/api/v1.0/posts/<string:id>/discussions/<string:discussion_id>/reply", methods = ["POST"])
def add_new_reply(id, comment_id):
    new_reply = {
        "_id" : ObjectId(),
        "username" : request.form["username"],
        "comment" : request.form["comment"]
        

    }
    post.update_one( 
        { "_id" : ObjectId(comment_id) }, 
        
        { 
            "$push": { "reply" : new_reply }
        }
    )
    new_reply_link = "http://localhost:5000/api/v1.0/posts/" + id + 
        "/comments/" + comment_id + "/reply/" + str(new_reply['_id'])
    return make_response( jsonify( { "url" : new_reply_link } ), 201 )

The structure of the post dataset is as follows:

Post

comment (array)
   
object

    reply (array)

    object
Asked By: Beth McCoy

||

Answers:

I think you are confused between layering of objects. You can use below query to push to your reply array field

post.update_one({
  "_id": <id of the post>,
  "comment._id": <id of the comment>
},
{
  $push: {
    "comment.$.reply": <your new_reply object>
  }
})

Mongo Playground

Answered By: ray
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.