@Pavel_Duchovny
Just to simplify few things, assume that in one collection each document has a type field. There exist exactly two types of documents:
type: "resource"type: "event"
Each event is associated to a specifc resource, so each document of type event has a property called resourceId which is valued with the _id property of the corresponding document of type resource.
In addition, each document of type resource has a property userId, that specifies the owner of that resource.
Now, having clearer in mind what is the design of the database, the goal is:
“When a new event is generated on a resource, create the event on database only if the user who generates the event is the owner of the corresponding resource”.
I would like to do this with in a single round-trip to the mongo server, with the following query:
let resourceId = "..."
let userId = "..."
let event = {...}
`db.editor.updateOne({_id: ObjectId(resourceId), type: "resource", $nor: [{userId: userId}]}, {$setOnInsert: event}, {upsert: true})`
Note that the event object does not have any _id property specified !! However, when the $setOnInsert is triggered, mongo tries to create a new document by inserting the _id that is specified in the query (i.e .: ObjectId (resourceId)). This generates a duplicate key error as I showed you above.
How can this be accomplished with a single round-trip?