I want to update an array in a document where array is array of user object.
The problem is i don't want to add duplicates in this array ( not the same user more than one time).
what i do :
const updatedTopic = await Topic.findByIdAndUpdate(
// @ts-ignore
{ _id: id, 'votes.user': { $ne: req.user?._id.valueOf() } },
// @ts-ignore
{ $push: { votes: { year, comment, user: req.user } } },
{ new: true }
);
But this isn't working as you can see below :
{
"name": "Argomento 1",
"exam": {
"$oid": "62b71b9dcaf3e92ac568c729"
},
"slug": "argomento-1",
"user": {
"$oid": "62534e5798a11bcba35464f6"
},
"votes": [
{
"year": 2022,
"comment": "",
"user": {
"$oid": "62b22fd314c40b9067f84cc2" -> same user
},
"_id": {
"$oid": "62b8bbcf876b2d27570fdf86"
}
},
{
"year": 2022,
"comment": "",
"user": {
"$oid": "62b22fd314c40b9067f84cc2" -> same user
},
"_id": {
"$oid": "62b8bbd5876b2d27570fdf89"
}
}
],
"createdAt": {
"$date": {
"$numberLong": "1656168790097"
}
},
"updatedAt": {
"$date": {
"$numberLong": "1656274729989"
}
},
"__v": 0
}
I don't know why but changing findByIdAndUpdate to findOneAndUpdate works fine.
Probably findByIdAndUpdate checks only the id condition.