Looking to make updates to a nested array within a document only if the item is not already included in the array:
await userCollection.findOneAndUpdate(
{ _id: ObjectId('616acc597ebda90ca6ffee21') },
{
'devices': {
$push: {
$cond: {
if: {
$in: [req.body.serial, '$devices']
},
then: '$devices',
else: { serial: req.body.serial, data: [] }
}
}
}
},
{ returnOriginal: false },
(err, _) => {
if (err) {
return res.status(400);
} else {
return res.status(200).json(user.value);
}
}
);
This represents my user object structure:
{
"_id": "616acc597ebda90ca6ffee21",
"username": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f783928483b783928483d994989a">[email protected]</a>",
"displayName": "Test",
"devices": [
{
"serial": "865674036421275",
"data": [
{
"timestamp": "2021-10-16T12:36:35.799Z"
},
{
"timestamp": "2021-10-16T12:41:33.633Z"
},
{
"timestamp": "2021-10-16T12:52:03.055Z"
}
]
},
],
"hashedPassword": "R5vt3vY7vEvTHvhC7YGNOWuIjBUQGLqsd92QGE06tjU=",
"salt": "6RS0OVIFboCkIEPHdZmTcQ==",
"dateCreated": "2021-10-16T12:58:00.294Z"
}
Is there a method to verify if the serial already exists within devices? And can an error be triggered if it does?