In the database, there is a Chats collection with a participants subdocument structured as follows:
{
_id: '1',
participants: [ { _id: 'A', seen: false }, { _id: 'B', seen: false } ],
messages: []
}
Each chat consists of only 2 participants, and one of them is always the currentUser, although which one is unknown. Additionally, each pair of users has only one chat associated with it.
When searching for a chat, both user ids are required. The query to find a chat looks like this:
Chats.find(
{ $and: [
{ participants: {$elemMatch: {_id: otherUserId}}},
{ participants: {$elemMatch: {_id: currentUserId}}}
]}
)
The goal is to allow the currentUser to update their own seen
field in a single operation.
Currently, the process involves finding the chat first, determining which participant represents the currentUser, creating a document to update that participant, and then updating it separately.
Is there a way to capture the id of the element matched with currentUserId, similar to using regex capture groups? For example...
Chats.update(
{ $and: [
{ participants: {$elemMatch: {_id: otherUserId}}},
{ participants: capture({$elemMatch: {_id: currentUserId}})}
]},
{
$set: {"participants.(capture[0]).seen": true}
})
Alternatively, is there a more efficient approach to achieve this?