I currently have a Chat model which has an array named deletedUsers containing objects with the following format: {deletionDate: Date, userId: Id}.
I want to delete a Chat document if the _id matches the specified id and if all the deletedUsers.deletionDate values are greater than the current date.
This is the query I currently have:
await Chat.findOneAndDelete({
$and: [{ _id: req.params.chatid }, {"deletedUsers.deletionDate": {$gt: Date.now()}}]
})
The problem with this query is that it will delete a document even if the deletionDate is greater than the current date for only one array element. I only want the document to be deleted if this is true for all array elements, not just one.
I attempted to use the $all operator with this query, however, I got an error perhaps due to an incorrect use case of this operator.
This is an example of what a deletedUsers array would look like for a typical Chat document:
deletedUsers array -
[{userId: Id, deletionDate: Date}, {userId: Id2, deletionDate: Date2}]
Any ideas on how to adjust this query to perform as expected? Thank you.
All array elements with
deletionDatemust be greater than the current date is equivalent to any array element(s) withdeletionDatemust not be less than or equal to the current date (Negation).Demo @ Mongo Playground