POST请求到嵌套查询 – Python API

huangapple go评论63阅读模式
英文:

POST request to a nested query - python API

问题

@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 )
英文:

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(&quot;/api/v1.0/posts/&lt;string:id&gt;/discussions/&lt;string:discussion_id&gt;/reply&quot;, methods = [&quot;POST&quot;])
def add_new_reply(id, comment_id):
    new_reply = {
        &quot;_id&quot; : ObjectId(),
        &quot;username&quot; : request.form[&quot;username&quot;],
        &quot;comment&quot; : request.form[&quot;comment&quot;]
        

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

The structure of the post dataset is as follows:

Post

comment (array)
   
object

    reply (array)

    object

答案1

得分: 0

我认为你对对象的分层有些混淆。你可以使用下面的查询将内容添加到你的 reply 数组字段中:

post.update_one({
  "_id": <帖子的ID>,
  "comment._id": <评论的ID>
},
{
  $push: {
    "comment.$.reply": <你的新回复对象>
  }
})

Mongo Playground

英文:

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

post.update_one({
  &quot;_id&quot;: &lt;id of the post&gt;,
  &quot;comment._id&quot;: &lt;id of the comment&gt;
},
{
  $push: {
    &quot;comment.$.reply&quot;: &lt;your new_reply object&gt;
  }
})

Mongo Playground

huangapple
  • 本文由 发表于 2023年2月24日 03:28:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定