In the beginning it is a chicken-egg problem, right? In order to link a comment
item to a parent
item you need to know the parent
-items _id
value. Which you only get after you created the parent
-item.
And to link the parent
-item to the comment
-item you need to know the comment
-items’ _id
, again only available after the comment
-items’ creation.
So the process seems to be
- POST create-parent-item without comment link
- now
parent-item._id
is known, e.g. 6128aa4e3630618af4000188
- POST create-comment-item with
{
"parentLink": {
"_id": "6128aa4e3630618af4000188",
"link": "parents",
"display": "entry 1"
}
...
}
- now
comment-item._id
is known, e.g. 6123b44c6138326b83000331
- GET parent-item current object to have the latest version of it
- extract and extend
commentsLink
array by new reference to new comment-item (I assume this is a 1:n multilink relationship)
{
"commentsLink": [
{
"_id": "6123b44c6138326b83000331",
"link": "comments",
"display": "comment 1"
}
],
...
}
- POST update-parent-item
/api/collections/parents/save
// param "data"
{
_id: "6128aa4e3630618af4000188",
"commentsLink": [
{
"_id": "6123b44c6138326b83000331",
"link": "comments",
"display": "comment 1"
}
]
}
BUT be aware, that due to the asynchronous nature of those request this scenario bears a high risk of race conditions where 2 comments at the same time get not properly linked, because they update the same parent item at the same time.
A cleaner solution would be to only save the parents-link in the comment-item when creating the new comment-item and then have a custom script triggered on-comment-item-save
to update the links in the related parent-item.
And in order to avoid repeating the race-condition-out-of-sync (only on a smaller scale) issue you might not only want to just add the current comment but “all lately (within the last seconds) created, related and not-linked-in-parent-yet” comments.
And maybe I overshot here.
But my answer to your question
You do this by having the collectionlink
fields data added into your HTTP POST requests.
First into the comment-item:
- POST
/api/collections/comments/save
+ data=NEW_COMMENTS_OBJECT_WITH_COLLECTION_LINK_FIELD_DATA
And then as an additional update to the related parents object
- POST
/api/collections/comments/save
+ data={_id: PARENTS_ITEM_ID*, commentsLink: [UPDATED_COLLECTIONLINK_DATA_ARRAY]}
*) having the _id
key set in a collections-save call triggers an “update” for which it is not necessary to post the whole object but is sufficient to only post the to-be-updated fields