英文:
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("/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
答案1
得分: 0
我认为你对对象的分层有些混淆。你可以使用下面的查询将内容添加到你的 reply
数组字段中:
post.update_one({
"_id": <帖子的ID>,
"comment._id": <评论的ID>
},
{
$push: {
"comment.$.reply": <你的新回复对象>
}
})
英文:
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>
}
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论