I have a collection of album documents like this:
[
{
_id: ObjectId(“6681e3a67077572b06828972”),
users: [{blocked: false, name: “Bill”], {blocked: true, name: “Gates”]],
maxUnblockedUserCount: 5
}
]
I want to push a user to the users array. This is only allowed if there aren’t too many unblocked users already in the users array, the limit set by the field maxUnblockedUserCount.
This is my update statement, however it does not take into account unblocked users:
Album.findOneAndUpdate(
{
_id: albumId,
$expr: {
$lt: [{ $size: “$users” }, “$maxUnblockedUserCount”],
},
},
{
$push: { users: { _id: userId, blocked: false} },
},
{ new: true }
)