I am building a forum web app where user can like/dislike post of other users.
I have the following model, representing a Post:
[
{
_id:"0002253,
title:"My first post",
likes:[],
dislikes:[]
},
{
_id:"0002254,
title:"My second post",
likes:[],
dislikes:[]
},
{
_id:"0002255,
title:"My third post",
likes:[],
dislikes:[]
},
]
When a user sends a like or dislike, the latter's ID will be inserted into the corresponding array (like or dislike).
Each user can, for each post, insert only a like or a dislike (not both).
The query I used for the insert is the following:
let vote_result = await Poll.updateOne(
{
_id: poll_id,
$and: [
{ "likes": { $nin: [MY_ID] } },
{ "dislikes": { $nin: [MY_ID] }},
],
},
{
$addToSet: {
"likes": MY_ID,
},
},
So, theoretically, query should insert MY_ID in likes or dislikes array if and only if MY_ID is not present in either array.
The problem is that query still writes MY_ID in likes array (even if MY_ID is present in dislikes) and vice versa.
Let's suppose now I want to leave a 'Like' to a post:
Phase 1:
likes:[]
dislikes:[]
(I am able to like or dislike, it works.)
Phase 2:
likes: [MY_ID]
dislikes:[]
(I am not able send like again, it works, but I am still able to dislike - it should not allow me to vote again.)