I need to update a field nested in my User document, that contains an array of part objects, to add new parts. One part object looks like this:
{
partId: 871838,
partNum: '87087',
partName: 'Brick Special 1 x 1 with Stud on 1 Side',
colorId: 0,
colorName: 'Black',
quantity: 10,
partImg: 'https:...'
}
I want to add the part to the array, but only if user doesn't already own it. I tried using $addToSet, like so:
await User.updateOne(
{ username: username },
{ $addToSet: { parts: { $each: req.body.parts } } }
);
but that won't work, since sometimes the part is the same, but the quantity varies, and that is enough to treat is as a different part, so it gets added. Is there a way to specify by which value to determine if the object already exists in an array?
EDIT: so, I found this in the docs :
you cannot specify that MongoDB compare only a subset of the fields in the document to determine whether the document is a duplicate of an existing array element
So that means that $addToSet is no good for my case... Now I have no idea what to do.